vue中组件之间的通信

1.父传子通过属性

<div id="#box">

  <one :abc="mytext"></one>

</div>

new Vue({

  el:"#box",

    data:{
  mytext:"hello"

},

components:{

  one:{

  template:`<div>{{abc}}</div>`,

  props:["abc"]


}
}


})

2.子传父通过事件

<div id="#box">

  <one @abc="handleClick></one>

    <input type="button" value="点击" ">

 <div v-show="isshow">123</div>

</div>

new Vue({

  el:"#box",

    data:{
  mytext:"hello",

    isshow:true

},

components:{

  one:{

  template:`<div><input type="button" @click=changeClick()/></div>`,

  methods:{
       changeClick(){
  this.$emit("abc")


  }
},

methods:{

 handleClick(){

  this.isshow=!this.isshow
}


}),

3.非父子之间的通信

<div id="#box">

</div>

 Vue.prototype.bus = new Vue()

new Vue({

 el:"#box",

  data:{

},

components:{
 one:{

  template:`<div> <input type="button" @click="handleClick()"/></div>`,

data(){

  return{
    mytext:"hello"
  }
 },

methods:{

  handleClick(){

  this.bus.$emit("one",this.mytext)
}

 }

},

two:{

  template:`<div></div>`,

  mounted:{

  this.bus.$on("on",(d)=>{

  console.log(d)
})
  }
}
})

原文地址:https://www.cnblogs.com/bamboopanders/p/12555689.html