vue 组件传值(二)$bus,$emit,$on
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="../node_modules/vue/dist/vue.min.js"></script>
<title>$bus</title>
</head>
<body>
<div id="app">
</div>
<script>
// new一个空的vue挂在到vue原型上
Vue.prototype.$bus = new Vue();
Vue.component('Child2',{
template : `<div>
<input type="text" v-model="msg">
</div>`,
data(){
return {
msg : ''
}
},
created(){
this.$bus.$on('myevent',(val)=>{
console.log('接受到来自兄弟一的数据'+val);
this.msg = val;
})
},
destroyed() {
//组件销毁前尽量关闭bus
this.bus.$off('myevent')
}
});
Vue.component('Child1',{
template : `<div>
<p>{{myprop}}</p>
<input type="text" @input="changeValue(myprop)" v-model="myprop">
</div>`,
data(){
return {
myprop : 'child1'
}
},
methods : {
changeValue(val){
this.$bus.$emit('myevent',val);
}
}
});
Vue.component('Parent',{
//记住template中只能有一个根元素,不然只显示第一个元素,后面都不显示
template: `<div>
兄弟一:<Child1></Child1>
兄弟二:<Child2></Child2>
</div>`,
});
new Vue({
el : '#app',
template : '<Parent><Parent>'
});
</script>
</body>
</html>
最重要的三句话:
(1)Vue.prototype.$bus = new Vue();
// new一个空的vue挂在到vue原型上
(2)this.$bus.$emit('myevent',val);
//需要传值的组件用
(3)接受传值的组件用:
this.$bus.$on('myevent',(val)=>{
console.log('接受到来自兄弟一的数据'+val);
this.msg = val;
})
该方式适用于兄弟组件直接传值使用。