<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<h1>{{msg}}</h1>
<test-a></test-a>
<test-b></test-b>
<button @click="handleOff">销毁事件</button>
</div>
<script>
var hub = new Vue()
Vue.component('test-a',{
data(){
return {
num:0
}
},
methods:{
handle(){
hub.$emit('test-b',3)
}
},
template:`<div>
<button @click="handle">aCom</button><span>{{num}}</span>
</div>`,
mounted(){
hub.$on('test-a',(val) =>{
this.num += val
})
}
})
Vue.component('test-b',{
data(){
return {
num:0
}
},
methods:{
handle(){
hub.$emit('test-a',2)
}
},
template:`<div>
<button @click="handle">bCom</button><span>{{num}}</span>
</div>`,
mounted(){
hub.$on('test-b',(val) =>{
this.num += val
})
}
})
new Vue({
data:{
msg:'helloworld'
},
methods:{
handleOff(){
hub.$off('test-a')
hub.$off('test-b')
}
}
}).$mount('#app')
</script>
</body>
</html>
Vue兄弟组件间通信
最新推荐文章于 2024-01-18 13:40:03 发布