這篇文章將為大家詳細講解有關怎么用vue父子組件同步傳遞和異步傳遞,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
1、同步傳遞數據
父組件 food 通過 props 把 值為 0 的 type 字段傳給子組件,子組件在初始化時可以拿到 type 字段,渲染出字符“0 水果”
// 父組件 food.vue
<template>
<apple :type="type"></apple>
</template>
<script>
data (){
return {
type: 0
};
}
</script>
// 子組件 apple.vue
<template>
<span>{{childType}}</span>
</template>
<script>
props: ['type'],
created () {
this.childType = this.formatterType(type);
},
method () {
formatterType (type) {
if (type === 0) {
return "0 水果";
}
if (type === 1) {
return "1 蔬菜";
}
return '';
}
}
</script>2 異步傳遞數據
要保證異步傳遞數據,根據VUE的雙向綁定原理,不難得知,異步傳遞的數據需要watch。
2.1 props
若props傳遞的數據關聯到模板中,則組件初始化時會watch該數據??梢娤旅娲a中的type和info。
若props傳遞的數據不關聯到模板,則為props傳遞的數據添加watch,在watch方法中修改關聯模板的對象??梢娤旅娲a中的child_type。此方法中,watch監聽到的是是發生變化的props,故需要對目標對象做初始化處理。
// 父組件 food.vue
<template>
<apple :type="type" :info="info"></apple>
</template>
<script>
data (){
return {
type: 0,
info: {comment: 'ugly food'}
};
}
created () {
setTimeout (()=>{
this.type = 1;
this.info = {comment: 'tasty food'};
},1000);
}
</script>
// 子組件 apple.vue
<template>
<p class="memuManage">
<span>type: {{child_type}}</span>
<span>type: {{type|formatterType}}</span>
<span>info: {{info.comment}}</span>
</p>
</template>
<script>
export default {
data () {
return {
child_type: ''
};
},
props: ["type","info"],
watch: {
type (newVal) {
this.child_type = this.formatterType(newVal);
}
},
created () {
this.child_type = this.formatterType(this.type);
},
filters: {
formatterType: function (type) {
if (type === 0) {
return "0 水果";
}
if (type === 1) {
return "1 蔬菜";
}
return '';
}
},
methods: {
formatterType (type) {
if (type === 0) {
return "0 水果";
}
if (type === 1) {
return "1 蔬菜";
}
return '';
}
}
};
</script>2.2 vuex
數據存放在store中,父組件調用vuex中的方法改變數據。
若store的數據關聯子組件的模板,則子組件初始化時會watch該數據。
若store的數據不關聯子組件的模板,則為store的數據添加watch,在watch方法中修改關聯模板的對象。需要對關聯模板的對象初始化。
3. 同步或異步傳遞數據
若父組件向子組件可能同步或異步傳遞數據,則首先子組件需要在created或者computed中對目標對象初始化,并且子組件中需要watch由props傳遞的數據,并修改目標對象。
關于怎么用vue父子組件同步傳遞和異步傳遞就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。