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該數據。可見下面代碼中的type和info。
若props傳遞的數據不關聯到模板,則爲props傳遞的數據添加watch,在watch方法中修改關聯模板的對象。可見下面代碼中的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>
<div class="memuManage">
<span>type: {{child_type}}</span>
<span>type: {{type|formatterType}}</span>
<span>info: {{info.comment}}</span>
</div>
</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傳遞的數據,並修改目標對象。