vue中非父子组件的传值

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>vue中非父子组件的传值(bus/总线/发布订阅模式/观察者模式)</title>
  <script src="vue.js"></script>
</head>
<body>
<div id="app">
  <child content="Dell"></child>
  <child content="Lee"></child>
</div>
<script>
  Vue.prototype.bus=new Vue()
  Vue.component('child',{
    
    
    template:'<div @click="handleClick">{
    
    {selfContent}}</div>',
    props:{
    
    
      content:String
    },
    data(){
    
    
      return {
    
    
        selfContent:this.content
      }
    },
    methods:{
    
    
      handleClick(){
    
    
        // alert(this.content);
        this.bus.$emit('change',this.selfContent);
      }
    },
    mounted:function(){
    
    
      var this_=this;
      this.bus.$on('change',function(msg){
    
    
        this_.selfContent=msg;
      })
    }
  });
  var app=new Vue({
    
    
    el:'#app'
  })
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/tozeroblog/article/details/85146116
今日推荐