非父子组件间的传值

非父子组件间的传值

1.Vuex

2.总线机制(Bus/发布订阅模式/观察者模式/)

Vue.prototype.bus=new Vue();

让原型属性bus指向一个Vue实例,让其充当非父子组件之间传值的桥梁,相当于计算机各种功能部件之间传送信息的公共通信干线(总线Bus)

1.给Vue类加上原型属性bus,这样每个vue实例都能访问到原型属性bus

2.利用bus的实例方法$emit触发事件

3.再利用生命周期方法(钩子)mounted给bus绑定舰艇函数,在事件触发时执行。

<body>
  <div id="root">
    <child content="Dell"></child>
    <child content="Lee"></child>
  </div>
  <script>
    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(){
          //alert(this.content)
          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'
    })
  </script>
 
</body>
posted @ 2019-12-19 20:46  嘘,在学习呢  阅读(238)  评论(0编辑  收藏  举报