非父子组件间的传值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非父子组件的传值(bus/总线、发布者订阅模式、观察者模式</title>
<script type="text/javascript" src="js/vue.js" ></script>
</head>
<body>
<div id="root">
<!--兄弟之间的关系如何进行传值呢 把上面的dell传给下面的li  通过总线传递-->
<child content="dell"></child>
<child content="li"></child>
</div>
<script>
Vue.prototype.bus = new Vue()//每调用Vue实例都会含有bus属性,bus是vue的实例
Vue.component('child',{
props:{
content:String
//参数校验
},
template:'<div @click="handleClick">{{content}}</div>',
methods:{
handleClick:function  () {
// alert(this.content);把弹出的内容传递出去


//$emit 里的参数第一个是事件名,第二个是传递的东西 emit来传递
this.bus.$emit('change',this.content)
}
},
mounted:function  () {//声明周期钩子函数来  监听传来的数据 on来监听bus触发的时间
var this_ = this 
this.bus.$on('change',function  (msg) {
this_.content = msg
//alert(msg)
})
}
})
var vm= new Vue({
el:"#root",

})
</script>
</body>

</html>

上面的值传给下面,但是报错了,以内墙改了父组件传来的值,所以要定义data函数在子组件里

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非父子组件的传值(bus/总线、发布者订阅模式、观察者模式</title>
<script type="text/javascript" src="js/vue.js" ></script>
</head>
<body>
<div id="root">
<!--兄弟之间的关系如何进行传值呢 把上面的dell传给下面的li  通过总线传递-->
<child content="dell"></child>
<child content="li"></child>
</div>
<script>
Vue.prototype.bus = new Vue()//每调用Vue实例都会含有bus属性,bus是vue的实例
Vue.component('child',{
data:function(){
return{
selfContent:this.content
}
},

props:{
content:String
//参数校验
},
template:'<div @click="handleClick">{{selfContent}}</div>',
methods:{
handleClick:function  () {
// alert(this.content);把弹出的内容传递出去


//$emit 里的参数第一个是事件名,第二个是传递的东西 emit来传递
this.bus.$emit('change',this.selfContent)
}
},
mounted:function  () {//声明周期钩子函数来  监听传来的数据 on来监听bus总线触发的事件
var this_ = this 
this.bus.$on('change',function  (msg) {
this_.selfContent = msg
//alert(msg)
})
}
})
var vm= new Vue({
el:"#root",

})
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41153478/article/details/80335819