父組件跟子組件之間的傳值(具體參考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); } }
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()接受參數