兄弟间的通信:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="vue.js"></script>
</head>
<body>
<div id="example">
{{msg}}
<xiongda></xiongda>
<hr>
<xionger></xionger>
</div>
<script type="text/x-template" id="brotherTpl1">
<div>
<h1>这是熊大</h1>
<button @click="tellXE">告诉熊二</button>
<hr>
</div>
</script>
<script type="text/x-template" id="brotherTpl2">
<div>
<h1>这是熊二</h1>
<button @click="tellXD">知道了</button>
<hr>
</div>
</script>
<script>
var bus = new Vue();
Vue.component("xiongda",{
template:"#brotherTpl1",
// 被动触发事件
mounted:function(){
bus.$on("xiongdaEvent",function(){
console.log("熊大收到消息了。。");
});
},
methods:{
tellXE:function(){
bus.$emit("xiongerEvent","光头强来了。");
}
}
});
Vue.component("xionger",{
template:"#brotherTpl2",
// 被动触发事件
mounted:function(){
bus.$on("xiongerEvent",function(msg){
console.log(msg);
});
},
methods:{
tellXD:function(){
bus.$emit("xiongdaEvent","知道光头强来了。");
}
}
});
new Vue({
el:"#example",
data:{
msg:'hello vuejs'
}
});
</script>
</body>
</html>