非父子组件传值

两个按钮, 点击上面的按钮,下面的数字+2
点击下面的按钮,上面的数字+1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<test-tom></test-tom>
<test-jerry></test-jerry>
<br>
<div>
<button @click="handle">销毁事件</button>
</div>
</div>
<script src="../js/vue.js"></script>
<script>
<!-- 提供事件中心-->
const hub = new Vue();
Vue.component('test-tom', {
data: function () {
return {
num: 0
}
},
template: `
<div>
<div>Tom:{{ num }}</div>
<div>
<button @click="handle">点击</button>
</div>
</div>
`,
methods: {
handle: function () {
//触发兄弟组件的事件
hub.$emit('jerry-event', 2)
}
},
mounted: function () {//勾子函数,当它被触发时,说明模板已经就绪了,可以对模板进行操作
// 监听事件
hub.$on('tom-event', (val) => {//等下会用到this
// 事件名称 , 接收传过来的数据
this.num += val;
});
}
})
Vue.component('test-jerry', {
data: function () {
return {
num: 0
}
},
template: `
<div>
<div>jreey:{{ num }}</div>
<div>
<button @click="handle">点击</button>
</div>
</div>
`,
methods: {
handle: function () {
//触发兄弟组件的事件
hub.$emit('tom-event', 1)
}
},
mounted: function () {//勾子函数,当它被触发时,说明模板已经就绪了,可以对模板进行操作
// 监听事件
hub.$on('jerry-event', (val) => {//等下会用到this
// 事件名称 , 接收传过来的数据
this.num += val;
});
}
})
const app = new Vue({
el: '#app',
data: {
},
methods:{
handle:function (){
hub.$off('tom-event');
hub.$off('jerry-event');
}
}
})
</script>
</body>
</html>

浙公网安备 33010602011771号