javascript - vue.js使用公共事件总线

查看:109
本文介绍了javascript - vue.js使用公共事件总线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在练习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

手机作答,就不写详细代码了,你应该懂了

这篇关于javascript - vue.js使用公共事件总线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆