一、建立两个平行的组件并在html中使用
新建两个平行的组件isay和ilisten,isay作为输入,ilisten作为输出
Vue.component('isay',{
template:`
<span>
<input type="text" v-model="saySomething" /><br/>
</span>
`,
data:function(){
return{
saySomething:'abc',
}
},
});
Vue.component('ilisten',{
template:`
<span>我听见了:{{listenSomething}}</span>
`,
data:function(){
return {
listenSomething:'',
}
},
});
<div id="app">
<isay></isay>
<ilisten></ilisten>
</div>
效果如下:
二、 给isay组件绑定keyup事件
并通过添加一个外部的事件调度器Event把事件里的值传出去
var Event= new Vue();
Vue.component('isay',{
template:`
<span>
<input @keyup="key_up()" type="text" v-model="saySomething" /><br/>
</span>
`,
data:function(){
return{
saySomething:'abc',
}
},
methods:{
key_up:function(){
Event.$emit('isaySomething',this.saySomething);
},
},
});
三、给ilisten组件添加mounted生命周期
使用Event.$on来获取调度函数中存的值
Vue.component('ilisten',{
template:`
<span>我听见了:{{listenSomething}}</span>
`,
data:function(){
return {
listenSomething:'',
}
},
mounted:function(){
var ilisten=this;
Event.$on('isaySomething',function(data){
ilisten.listenSomething=data;
});
},
});