根据千峰教育学习视频所练习的笔记 | 学习一段时间,我也有写一点东西的必要了···html
<div>
里面写两个组件,<dear-feifei>
和<dear-zhangliuping>
,这两个组件就是非父子组件的关系。如今我想在在<dear-zhangliuping>
进行了一些操做,怎样能将数据传入到<dear-feifei>
当中。<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue 非父子组件通讯</title> <script src="../vue.js"></script> </head> <body> <div id="app"> <dear-feifei></dear-feifei> <dear-zhangliuping></dear-zhangliuping> </div> <script> var vm = new Vue({ el:'#app', components:{ 'dear-feifei':{ template:'<h2>{{message}}</h2>', data:function () { return{ message:'hello feifei' }; }, }, 'dear-zhangliuping':{ template:'<ul><li v-for="item in list">{{item}}</li></ul>', data:function () { return{ list:['哈哈','呵呵','吼吼'] }; }, } } }); </script> </body> </html>
<dear-zhangliuping>
组件中添加一个事件:template:'<ul><li @click="getContent" v-for="item in list">{{item}}</li></ul>',
<dear-feifei>
里面。咱们还需在开头建立一个空实例,就能够调用这个实例的 $emit 添加自定义事件来进行触发var busVm = new Vue(); //定义空实例 <script> ······ 'dear-zhangliuping':{ template:'<ul><li @click="getContent" v-for="item in list">{{item}}</li></ul>', data:function () { return{ list:['哈哈','呵呵','吼吼'] }; }, methods:{ getContent:function (ev) { busVm.$emit('changeEvents',ev.target.innerHTML); } } ······ </script>
<dear-feifei>
里面经过生命周期进行订阅,用mounted。在里面用 $on 来接收事件。<script> 'dear-feifei':{ template:'<h2>{{message}}</h2>', data:function () { return{ message:'hello feifei' }; }, mounted:function () {//用于接收分发过来的数据 busVm.$on('changeEvents',function (str) { console.log(str); }); } }, </script>
mounted:function () { busVm.$on('changeEvents',function (str) { console.log(str); this.message = str; <!-- this 指向busVM这个对象,要去修正,以指向dear-feifei --> }.bind(this));//绑定之后就指向dear-feifei了 }
这样就完成了非父子组件通讯vue
在想要接收的位置,用 $on 的方式进行接收,造成一个发布与订阅的模式,来实现数据的交互,就完成了非父子组件的通讯vuex
上面的方法能解决简单的项目,但稍微复杂一点的项目咱们就用vuex的方法了app
<div>
容器里写两个组件<div id="app"> <div>{{count}}</div> <addbtn></addbtn> <removebtn></removebtn> </div> <script> var busVm = new Vue(); var vm = new Vue({ el:'#app', data:{ count:0 }, components:{ 'addbtn':{ template:'<button >+</button>', }, 'removebtn':{ template:'<button >-</button>', } } }); </script>
<div id="app"> <addbtn :count="count"></addbtn> <removebtn :count="count"></removebtn> </div> <script> components:{ ····· 'addbtn':{ template:'<button >+</button>', props:['count'], </script>
<script> ······ components:{ 'addbtn':{ template:'<button @click="setCount">+</button>', props:['count'], methods:{ setCount:function () { busVm.$emit('changeEvents',this.count+1); } } }, 'removebtn':{ template:'<button @click="setCount">-</button>', props:['count'], methods:{ setCount:function () { busVm.$emit('changeEvents',this.count-1); } } } } }); </script>
var busVm = new Vue(); //定义空实例 var vm = new Vue({ el:'#app', data:{ count:0 }, mounted:function(){ busVm.$on('changeEvents',function (num) { this.count = num; }.bind(this)); },