在練習vue框架的使用,在寫一個todo的demo,我把input元素(new-input元件)和展示待辦事項的ul,li元素( todo-items和todo-item元件)寫成了兩個平行的元件,現在在input元件中輸入文字添加,使用公共事件匯流排觸發update事件,在todo-items元件的生命週期中建立鉤子函數監聽update事件並修改元件中的數據,這時問題來了,報錯顯示該元件的todos陣列為undefined
下面貼程式碼
var bus = new Vue({});
var todoItem = Vue.component('todo-item', {
props:['todo'],
template:'<li class="animated fadeIn cusFont" v-bind:class="{ done:isDone }"><span><button class="done" v-on:click="done" v-bind:class="{doneButton: isDone}"></button></span><p v-bind:class="{doneItem:isDone}">{{todo.text}}</p><button class="delete" v-on:click="deleteIt">×</button></li>',
data:function(){
return {
isDone:false
}
},
methods:{
done:function(){
this.$emit('hasDone');
this.isDone = !this.isDone;
},
deleteIt:function(){
this.$emit('hasDelete');
}
}
});
var todoItems = Vue.component('todo-items', {
template:'<ul><todo-item v-for="(item, index) in todos" v-bind:todo="item" v-on:hasDelete="deleteItem(index)"></todo-item></ul>',
data:function(){
return {
todos:[
{text:'nodeJS'},
{text:'vue.js'}
]
}
},
components:{
'todo-item':todoItem
},
methods:{
deleteItem:function(index){
this.todos.splice(index, 1);
},
update:function(value){
this.todos.push(value);
}
},
created(){
bus.$on('updateData', function(value){
this.todos.push(value);
})
}
})
var newInput = Vue.component('new-input', {
template:'<input ref="input" placeholder="What needs to be done?" id="js-input-item" v-bind:value="value" class="animated fadeIn cusFont" v-on:keyup.enter="update">',
data:function(){
return {
value:''
}
},
methods:{
update:function(){
bus.$emit('updateData', {text:this.$refs.input.value});
}
}
})
var todo = new Vue({
el:'#todo',
components:{
"todo-items":todoItems,
"new-input":newInput
}
})
不知道什麼原因,todo-items中的deleteItem方法又可以操作todos數組。
手機回答
問題主要出現在bus.$emit那,bus是新的實例Vue,他的this沒有todos,應該這樣
created裡面:
const that = this
之後bus裡面的 this改為that
手機作答,就不寫詳細程式碼了,你應該懂了
bus實例監聽的回呼函數裡的this指向並不是你所期望的那個vue實例,解決方法就是樓上說的