<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>非父子组件间的传值(Bus/发布订阅模式/观察者模式/总线)</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <zyx content='zyx'></zyx> <zyx content='zy'></zyx> </div> </body> <script> /* 把Vue实例赋值给 Vue.prototype 的 bus 属性上 ,以后每次调用Vue或者创建组件的时候,都会有bus这个属性。 因为new的实例或者组件都是通过Vue这个类创建的。 在Vue的prototype上挂载了bus属性 */ Vue.prototype.bus = new Vue(); Vue.component('zyx',{ data:function(){ return { selfContent : this.content //因为子组件的props里的值不能修改父组件,所以先把值赋值给另一个变量 } }, props:{ content:String //content必须是个string类型 }, template:'<div @click="clickHander()">{{selfContent}}</div>', methods: { clickHander(){ //向bus上触发一个change事件,并把参数传递过去 this.bus.$emit('change',this.selfContent) } }, //监听生命周期函数 // created:在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图。 // mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。 mounted:function(){ //监听change事件 var _this = this; this.bus.$on('change',function(msg){ _this.selfContent = msg; }) }, }) let vm = new Vue({ el:'#app', }); </script> </html>
Vue—非父子组件间的传值(Bus/发布订阅模式/观察者模式/总线)
猜你喜欢
转载自www.cnblogs.com/bearSky/p/11970335.html
今日推荐
周排行