标签:handle 操作 doctype 执行 cti pre doc return on()
Vue非父子组件传值(Bus/总线/发布订阅模式/观察者模式)
我们在之前已经知道了父子传值。父组件传递过来了的值,在子组件通过props接受,然后就可以使用了。
也学过了隔代传值,均是通过props逐层传递实现。那么,兄弟节点之间怎么传值呢?

通过bus实现方式如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<child content=‘Dell‘></child>
<child content=‘Lee‘></child>
</div>
<script src="js/vue.js"></script>
<script>
//给每个Vue绑定一个bus属性,其实他是一个Vue实例
Vue.prototype.bus = new Vue()
Vue.component(‘child‘,{
data:function() {
return {
//为了避免直接修改父组件传过来的值,把父组件的值来一份拷贝
msg:this.content
}
},
props:{
content:String
},
template:‘<div @click="handleClick">{{msg}}</div>‘,
methods:{
handleClick:function(){
//子组件会向父组件触发change事件,同时把msg传过去
this.bus.$emit(‘change‘,this.msg)
}
},
//这个组件挂载的时候,会执行的一个函数
mounted:function(){
//通过bus监听change事件,当change事件触发的时候,进行操作
var this_ = this
this.bus.$on(‘change‘,function(message) {
console.log(message)
this_.msg=message
})
}
})
// 1. 创建Vue的实例
let vm = new Vue({
el: ‘#app‘,
});
</script>
</body>
</html>
Vue非父子组件传值(Bus/总线/发布订阅模式/观察者模式)
标签:handle 操作 doctype 执行 cti pre doc return on()
原文地址:https://www.cnblogs.com/skyflask/p/10985963.html