Vue-发布订阅机制(bus)实现非父子组件的传值

<!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>Document</title>
</head>
<body>
  <div id="app">
    <child :content="'全部变成第1项内容'"></child>
    <child :content="'全部变成第2项内容'"></child>
  </div>
</body>
<script type="text/javascript" src="./vue.js"></script>
<script
<!-- 把Vue.prototype上挂载一个bus属性,这个属性指向1个vue实例,
以后创建组件的时候,每个组件上都会有bus这个属性,都指向同一个实例 -->
Vue.prototype.bus=new Vue();
Vue.component('child',{
  props:['content'],
  template:"<div @click='handleClick'>{{selfContent}}</div>",
  data:function(){
    return {
      selfContent:this.content
    }
  },
  methods:{
    handleClick:function(){
      //本组件向外触发change,并携带值
      this.bus.$emit('change',this.content);
    }
  },
  mounted:function(){
    var this_=this
    //其它组件监听change,并取得值
    //两个child的组件都对change进行了监听
    this.bus.$on('change',function(msg){
      console.log('change');
      this_.selfContent=msg;
    })
  }
})
var app=new Vue({
    el:'#app',
})
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/superlizhao/p/9629663.html