- 在一些項目需求中需要父組件向子組件動態(tài)傳值,比如父組件動態(tài)通過axios獲取數(shù)據(jù),然后傳給子組件,子組件根據(jù)拿到的數(shù)據(jù)進(jìn)行展示。
- props傳值的時候,只會首次傳遞綁定的值,不會變化
方式1
- 利用watch監(jiān)聽props變化
// 子組件
props: {
params: {
type: String,
default: '',
required: true
}:
xxx: {
type: Array, // 當(dāng)props為數(shù)組或者對象的時候,要通過工廠函數(shù)的形式來設(shè)置默認(rèn)值
default() {
return []
}
}
},
data() {
return {
xxx : '' // 可以再computed中對相關(guān)數(shù)據(jù)進(jìn)行處理
}
},
watch:{ // 監(jiān)聽
params(curVal,oldVal){
if(curVal){
this.xxx=curVal;
}
},
}
方式2
- 利用ref獲取子組件,調(diào)用子組件的方法將值傳遞過去
// 父組件,調(diào)用子組件方法
<Child ref="mychild" :src-list="xxx"/>
mounted(){
// 通過axios獲取數(shù)據(jù),假設(shè)為rr
this.$refs.mychild.getParentData(rr)
}
// 子組件,定義方法
getParentData(val) {
this.xxx = val; // 將父組件的數(shù)據(jù)放到自己的data中
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-603151.html
文章來源:http://www.zghlxwxcb.cn/news/detail-603151.html
到了這里,關(guān)于vue中組件動態(tài)傳值,實現(xiàn)數(shù)據(jù)實時更新的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!