Vue父子组件和非父子组件各类通信总结

父组件跟子组件之间的传值(具体参考lonzhubb商城)https://www.jianshu.com/p/bc07a3478313

1、父组件传值给子组件形式,ifshop是要传的对象,右边ifshop代表要传的这个对象的数据,如果只是传常量,那么属性可以不用加':'(表示动态)

<v-select  :ifshop="ifshop"  :clickType="clickType" @close="close" @addShop="sureAddShop"></v-select>

2、子组件接收父组件的数据用props(直接接受父组件传过来的数值,data不需要再定义变量接收)

props: {

 ifshop:{
      type:Boolean,
      default (){
           return false
      }
}

}

3、子组件调用父组件

methods: {
close:function(){
this.$emit('close');
},

父组件接受子组件传过来的参数可以是一个个接收的

this.$emit('sureSelect',this.select,this.num,this.changePrice,this.changeKeyname);   //传值
sureSelect:function(keyId,num,price,keyName){}  //接收

4、非父组件跟子组件之间的传值,还有父组件调用子组件中的事件也是同样的(事件总线)

之间值

创建事件总线的方法

方法一:直接在main.js建一个空的Vue实例,用来做中央事件总线

//购物车组件信息交互
Vue.prototype.shopbus = new Vue();

在组件A中传递参数

methods: {
     add:function(){
          this.shopbus.$emit('goodsCount',this.myCount);
     }
}
 
在组件B中接收参数
created() {
     this.shopbus.$on('goodsCount', (myCount) => {} )
}

 在使用完,要销毁的时候,需要销毁

// 最好在组件销毁前
// 清除事件监听
beforeDestroy () {
 this.$bus.$off('todoSth');
}

方法二:可以新建一个js文件(bus.js),文件内容如下

import Vue from 'vue';

// 使用 Event Bus
const bus = new Vue();

export default bus;

在需要接受bus的文件中

通过 import bus from './bus';引用

然后通过bus.$on()接受参数

原文地址:https://www.cnblogs.com/qdlhj/p/8859067.html