【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
方法二、$emit/$on
这种方法通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级。当我们的项目比较大时,可以选择更好的状态管理解决方案vuex。
1.具体实现方式:
var Event=new Vue(); Event.$emit(事件名,数据); Event.$on(事件名,data => {});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<hello1></hello1>
<hello2></hello2>
</div>
<script>
var Event= new Vue();
Vue.component("hello1",{
template:'<h2 v-on:click="startHandle">send</h2>',
methods:{
startHandle:function(){
console.info("send");
Event.$emit('data-a','hello');
}
}
});
var Event= new Vue();
Vue.component("hello2",{
template:"<h2>receive</h2>",
methods:{
printVal:function(val){
console.info("printVla:"+val)
}
},
mounted(){
Event.$on('data-a',name=>{
console.info('receive:'+name);
this.printVal(name);
})
}
});
new Vue({
el:"#app"
});
</script>
</body>
</html>
来源:oschina
链接:https://my.oschina.net/u/4157150/blog/3149209