深入了解 Vue 组件(三)

版权声明:转载请注明出处 https://blog.csdn.net/SOALIN228/article/details/84846234

非父子组件间传值

定义一个bus属性,将他绑定到 prototype 上,这样每个 Vue 实例都会有 bus 这个属性,通过 bus 来向外触发事件,使用 methods 在被挂载的时候执行,需要注意的是因为作用域发生了变化所以不能直接使用 this ,记得不要修改父组件传过来的值哦


<child content="hello"></child>
<child content="world"></child>
Vue.prototype.bus = new Vue()

Vue.component('child', {
   data: function() {
     return {
       selfContent: this.content
     }
   },
   props: {
     content: String
   },
   template: '<div @click="handleClick">{{selfContent}}</div>',
   methods: {
     handleClick: function() {
       this.bus.$emit('change', this.selfContent)
     }
   },
   mounted: function() {
     var this_ = this
     this.bus.$on('change', function(msg) {
       this_.selfContent = msg
     })
   }
 })

 var vm = new Vue({
   el: '#root'
 })

猜你喜欢

转载自blog.csdn.net/SOALIN228/article/details/84846234