一. 子組件向父組件傳值 - $emit
發(fā)射事件
父子組件傳值.png
1. 子組件$emit
發(fā)射事件A
this.$emit(event,...argument);
/*
* event: 要觸發(fā)的事件
* argument: 傳給父組件的參數(shù)
*/
例子:this.$emit('emitEvent',data,'lalala');
2. 父組件通過(guò)事件名A接收
<part-template @emitEvent = "ievent"></i-template>
methods:{
ievent(...data){
console.log('allData:',data); // data為包含傳過(guò)來(lái)所有數(shù)據(jù)的數(shù)組辜王,第一個(gè)元素是對(duì)象勺鸦,第二個(gè)元素是字符串
}
}
二. 父組件向子組件傳值 - props
傳值
1. 在父組件import引入封裝出去的子組件
import dialogAttendee from "../../activity/component/dialogAttendee";
2. 在父組件視圖模板中到涂,通過(guò) : 變量 占位傳值
<dialogAttendee :dialogcascaderVisible="dialogcascaderVisible" @dialogClose="dialogClose"></dialogAttendee>
3. 在子組件通過(guò)props
接收值树肃,像本組件的data中定義的變量一樣使用(this獲取)
props:{
dialogcascaderVisible: {
type: Boolean,
default: false
},
reservation:Array,
}
三. watch
監(jiān)聽(tīng)值變化
- watch是一個(gè)對(duì)象泽腮,有鍵(要監(jiān)聽(tīng)的對(duì)象)拼苍,值(對(duì)象發(fā)生變化玖姑,執(zhí)行的函數(shù)端朵。
- 值可以是函數(shù)社付,也可以是函數(shù)名承疲。
data: {
c: {
name: '小強(qiáng)',
age: 20,
sex: '男'
},
tdArray:["1","2"],
},
watch: {
a: function (val, oldVal) { //新值,舊值
console.log('new: %s, old: %s', val, oldVal)
},
b: 'someMethod', // 函數(shù)名
c: { // 包括選項(xiàng)的對(duì)象
handler: function (val, oldVal) { /* ... */ }, //監(jiān)聽(tīng)變化時(shí)執(zhí)行回調(diào)函數(shù)
deep: true鸥咖,//監(jiān)聽(tīng)對(duì)象的屬性燕鸽,需要深度監(jiān)聽(tīng);數(shù)組不需要啼辣。
immediate: true
}
'c.name':function(val,oldval){ //鍵路徑必須加引號(hào)
console.log(val+"aaa")
}
}
四. 注意事項(xiàng)
- 在Vue2中組件的
props
的數(shù)據(jù)流動(dòng)只能單向流動(dòng)啊研。即只能由組件外(調(diào)用組件方)通過(guò)組件的DOM屬性attribute傳遞props給組件內(nèi),組件內(nèi)只能被動(dòng)接收組件外傳遞過(guò)來(lái)的數(shù)據(jù)鸥拧,并且在組件內(nèi)党远,不能修改由外層傳來(lái)的props數(shù)據(jù)。- 父組件可以通過(guò)自定義屬性向子組件傳值富弦;子組件通過(guò)
props
來(lái)接收沟娱;子組件不能直接修改父組件傳遞過(guò)來(lái)的數(shù)據(jù);子組件可以通過(guò)$emit()
方法去間接調(diào)用父組件中的方法去更改父組件中的數(shù)據(jù)腕柜。
五. 父組件引用封裝出去的子組件
<template>
<div>
<testComponent></testComponent> <!-- 3.通過(guò)定義的子組件名以標(biāo)簽形式直接使用 -->
</div>
</template>
<script>
import testComponent from './testComponent.vue' //1.先使用import導(dǎo)入你要在該組件中使用的子組件
export default {
components: {testComponent}, //2.然后在components屬性中寫(xiě)入子組件
methods: {},
}
</script>
六. 動(dòng)態(tài)組件
1.通過(guò)使用預(yù)定義的標(biāo)簽
< compnent >
可以動(dòng)態(tài)的綁定其is
特性济似,使得多個(gè)組件有一個(gè)共同的掛載點(diǎn)矫废,實(shí)現(xiàn)動(dòng)態(tài)切換。
< keep-alive >
標(biāo)簽會(huì)把切換出去的組件保留在內(nèi)存中砰蠢,可以保留它的狀態(tài)或避免重新渲染蓖扑。
<button @click="toggle('home')">顯示主頁(yè)</button>
<button @click="toggle('list')">顯示列表頁(yè)</button>
<keep-alive>
<component :is="currentView"></component>
</keep-alive>
//修改currentView變量,切換組件名
methods: {
toggle(com) { this.currentView = home; }
}
七. 兄弟組件傳值:bus總線
傳值
- 非父子組件之間不能直接通訊台舱,必須使用“代理人”赵誓,即中央數(shù)據(jù)總線過(guò)渡。
var bus = new Vue();
- A組件向B組件傳值柿赊,A組件中要通過(guò)bus總線觸發(fā)相應(yīng)的事件俩功;
bus.$emit('sendtoTwo', this.one)
- B組件要在鉤子函數(shù)中監(jiān)聽(tīng)相應(yīng)的事件。
mounted() { // 監(jiān)聽(tīng)sendtoTwo, 事件監(jiān)聽(tīng)也可以寫(xiě)到created鉤子函數(shù)
bus.$on('sendtoTwo', (data) => {
this.two = data;
})
}