我需要幫助。我是 Vue3 的業余愛好者,無法理解為什么會發生這種情況:
如果我在父組件中設定它:
props: [ 'code' ],
data() {
return {
asset: {
id: '',
brand: '',
group: {
name: '',
area: ''
}
}
}
},
created() {
axios.get('/api/myUrl/' this.code, {})
.then(response => {
if (response.status === 200) {
this.asset = response.data;
}
})
.catch(error => {
console.log(error);
})
}
然后,在我的組件中<asset-insurance :asset_id="asset.id"></asset-insurance>,asset_id 道具為空。
但是,如果我設定:
props: [ 'code' ],
data() {
return {
asset: []
}
},
created() {
axios.get('/api/myUrl/' this.code, {})
.then(response => {
if (response.status === 200) {
this.asset = response.data;
}
})
.catch(error => {
console.log(error);
})
}
然后,asset_id 道具在組件內獲得正確的asset.id值<asset-insurance>,但我在主組件中收到一些警告和錯誤,關于資產屬性 group.name 未設定(但它在模板中正確呈現)。
可能我做錯了什么,但我找不到問題出在哪里。有什么幫助嗎?
編輯:
我只是通過 console.logging 檢查子組件 AssetInsurance 中的道具
<script>
export default {
name: "AssetInsurance",
props: [
'asset_id'
],
created() {
console.log(this.asset_id)
}
}
</script>
asset_id 只是一個整數,并且在父級的資料 asset.id 中被正確分配,因為我也在父級模板中呈現它。
uj5u.com熱心網友回復:
定義asset為陣列并用普通物件重新分配它是不正確的。這可能會影響反應性,并且還會阻止group讀取嵌套的鍵。
問題被誤診了。asset_id值已更新,但不是在預期的時間更新。組件實體創建時prop值是不可用的,在 中檢查prop值是不正確的created,特別是因為它是異步設定的。
為了asset_id在控制臺中輸出最新值,應該使用觀察者,這就是它們的用途。否則asset_id可以按原樣在模板中使用。
uj5u.com熱心網友回復:
好吧,我想我找到了正確的方法,至少在我的情況下。
Prop 在組件中不可用,因為它是在組件創建后生成的,正如@EstusFlask 所指出的。
對此的簡單解決方法是僅在 prop 可用時才安裝組件:
<asset-insurance v-if="asset.id" :asset_id="asset.id"></asset-insurance>
這樣,組件可以毫無問題地運行,并且我可以按我應該的方式宣告物件。:)
謝謝你,埃斯圖斯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380345.html
上一篇:根據條件查找所有索引
