<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>兄弟之间的通讯问题</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<one></one>
<two></two>
</div>
<script>
//创建中央事件总线。
var bus =new Vue();
// 组件one
Vue.component('one',{
template:'<button v-on:click="oneFn">点击+</button>',
data:function () {
return{
oneNum:0
}
},
// 为组件one创建方法,用来触发事件common(common是中央事件总线bus的自定义事件名称,只需要与two中的监听事件名称一致即可。
methods:{
oneFn:function () {
bus.$emit("common", this.oneNum+=1)//此处的参数即为two中监听事件中传入的参数(n),此处(触发)的this指的是组件one,而在(监听)的this指的是bus。
}
}
});
// 组件 two
Vue.component('two',{
template:'<p>{{twoNum}}</p>',
data:function () {
return {
twoNum:0
}
},
// 为组件two创建钩子,挂载$on监听事件,
created:function () {
var self = this;//将this赋值给self。
bus.$on('common',function (n) {
self.twoNum = n;//此处为self,表示是组件two的变量,若为this,则表示是bus的变量。
})
}
});
new Vue({
el:'#app'
})
</script>
</body>
</html>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有