vue中的非父子间的通讯问题(简单的实例)

来源:互联网 发布:电脑管理软件 知乎 编辑:程序博客网 时间:2024/05/16 12:19

官网上的例子好晦涩,看了一个头两个大,关于非父子间的通讯问题,经过查阅得到了下面的例子,

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>兄弟之间的通讯问题</title>    <script src="vue.js"></script></head><body><div id="app"><one></one><two></two></div><script>    //创建中央事件总线。        var bus =new Vue();//    组件one    Vue.component('one',{        template:'<button v-on:click="oneFn">点击+</button>',        data:function () {            return{                oneNum:0            }        },//        为组件one创建方法,用来触发事件common(common是中央事件总线bus的自定义事件名称,只需要与two中的监听事件名称一致即可。        methods:{            oneFn:function () {                     bus.$emit("common", this.oneNum+=1)//此处的参数即为two中监听事件中传入的参数(n),此处(触发)的this指的是组件one,而在(监听)的this指的是bus。            }        }    });//    组件 two    Vue.component('two',{        template:'<p>{{twoNum}}</p>',        data:function () {         return  {             twoNum:0         }        },//        为组件two创建钩子,挂载$on监听事件,        created:function () {            var self = this;//将this赋值给self。            bus.$on('common',function (n) {                self.twoNum = n;//此处为self,表示是组件two的变量,若为this,则表示是bus的变量。            })        }    });new Vue({    el:'#app'})</script></body></html>

我也是新手,刚开始自学Vue,上面有不懂的童鞋请留言,一起进步!

原创粉丝点击