vue.js 无法读取data 数据里面的item

Uncaught TypeError: Cannot read property 'items' of undefined

不论用this.items还是 items 都无法读取,并且奇怪的是type==1 里面可以用this.items 读取到data里面的items 但是type==2里面就不行了 不知道为啥 求教我
<button type="button" id="allNotes" v-on:click="showNote(1)">

             <span>allNotes</span>
         </button>
         <button id="Favorites" v-on:click="showNote(2)">
             <span>Favorites</span>
         </button>
         
         
         

export default {

    data:function(){
        return{
            items:this.$parent.Notes,
        }
    },
    methods:{
        showNote:function(type){
            this.items='';
            if(type==1){
                this.items=this.$parent.Notes;
            }
            if(type==2){
                this.$parent.Notes.forEach(function(c){
                    if(c['favorite']){
                        console.log(this.items);
                        
                    }
                });
            }
        }
阅读 6.2k
5 个回答
this.$parent.Notes.forEach(c => {
                    if(c['favorite']){
                        console.log(this.items);
                        
                    }
                });
新手上路,请多包涵

你可以试一下 else if

图片描述
在type == 2 那个里 你调用了 循环,在循环里this不是指的vue实例
所以才会报错

if(type==2){
            let that = this;
            this.$parent.Notes.forEach(function(c){
                if(c['favorite']){
                    console.log(that.items);
                    
                }
            });
  }
  或者用箭头 

是不是this的指向问题?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题