組件間傳值
- props、$emit
- $attrs、$listeners
- provide、inject
- vuex(暫不展開)
一、父子組件間傳值
(1)父組件向子組件傳值(通過 props 屬性)
- 父組件直接在子組件標(biāo)簽上傳值
<div>
<child :value='message'><child>
</div>
import Child from './Child.vue'
components: {
Child
},
- 子組件通過 this.value 來獲取值
// 定義屬性
props: [ 'value' ],
created() {
let msg = this.value
console.log(msg)
}
(2)子組件向父組件傳值(通過 emit 事件)
- 子組件
<div @click="confirm">確定</div>
confirm() {
this.$emit('confirm', this.value);
},
- 父組件
通過 @confirm="onConfirm" 把子組件的事件傳遞給父組件的自定義事件
<div>
<child
:value="message"
@confirm="onConfirm">
</child>
</div>
onConfirm (value) {
let msg = value;
console.log(msg);
},
二、祖先后代組件間傳值
使用【$attrs、$listeners】或【provide、inject】
如果我們有:A組件(父) -> B組件(子) -> C組件(孫),而我們只是想把A組件的信息傳遞給C組件,如果使用props來傳遞信息,雖然能夠?qū)崿F(xiàn),但是代碼不夠美觀。在vue2.4中,為了解決該需求,引入了$attrs 和 $listeners和inheritAttrs(默認(rèn)true,標(biāo)簽元素中是否繼承父組件傳遞過來的屬性)。
(1)$attrs、$listeners
$attrs包含了父作用域中非 props 特性綁定的屬性 (class 和 style 除外)。它可以通過 v-bind="$attrs" 將屬性傳入內(nèi)部組件。
$props包含了父作用域中 props 特性綁定的屬性 (class 和 style 除外)。
$listeners包含了父作用域中 (不含 .native 修飾器的) v-on 事件監(jiān)聽器。它可以通過 v-on="$listeners" 將事件監(jiān)聽指向這個組件內(nèi)的子組件。
- 父組件
<div id="app">
<!-- 父組件調(diào)用子組件 -->
<child :name="111" :age="18" :city="'北京'" @ffunc="fatherFunction"></child>
</div>
function fatherFunction() {
console.log('父組件 function!!!')
}
- 子組件
<div>
<!-- 子組件通過$attrs獲取屬性值 -->
姓名:{{ $props.name }} - 年齡:{{ $attrs.age }} - 城市:{{ $attrs.city }}
<!-- 子組件通過 v-bind="$attrs" 將屬性傳入內(nèi)部組件,通過 v-on="$listeners" 將事件監(jiān)聽指向這個組件內(nèi)的子組件 -->
<son :msg="333" v-bind="$attrs" v-on="$listeners"></son>
</div>
inheritAttrs: true, // 標(biāo)簽元素中是否繼承父組件傳遞過來的屬性
props: [ 'name' ],
created() {
console.log(this.$attrs, this.$props);
this.$emit('ffunc')
}
- 孫組件
<div>
<!-- 孫子組件通過$attrs獲取屬性值 -->
消息:{{ $props.msg }} - 年齡:{{ $attrs.age }}
</div>
inheritAttrs: false, // 標(biāo)簽元素中是否繼承父組件傳遞過來的屬性
props: [ 'msg' ],
created() {
console.log(this.$attrs, this.$props);
this.$emit('ffunc')
}
inheritAttrs(默認(rèn)true,標(biāo)簽元素中是否繼承父組件傳遞過來的屬性)

(2)provide、inject
假如有一些深度嵌套的組件,而深層的子組件只需要父組件的部分內(nèi)容。在這種情況下,如果仍然將 prop 沿著組件鏈逐級傳遞下去,可能會很麻煩。
對于這種情況,我們可以使用一對 provide 和 inject。無論組件層次結(jié)構(gòu)有多深,父組件都可以作為其所有子組件的依賴提供者。這個特性有兩個部分:父組件有一個 provide 選項來提供數(shù)據(jù),子組件有一個 inject 選項來開始使用這些數(shù)據(jù)。
- 父組件
<div id="app">
<!-- 父組件 -->
<child></child>
</div>
data () {
return {
name: '我是父組件的數(shù)據(jù)',
age: '',
city: ''
}
},
provide() { // 父組件提供數(shù)據(jù)(只需要name字段數(shù)據(jù))
return {
user: this.name
}
},
- 子組件
<son></son>
- 孫組件
<div>
獲取父組件的數(shù)據(jù):{{ user }}
</div>
inject: ['user'], // 子組件使用數(shù)據(jù)
created() {
console.log(this.user)
}