1 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
這里有幾個(gè)問題。
該data
函數(shù)僅在創(chuàng)建相應(yīng)的 Vue 實(shí)例時(shí)調(diào)用一次。在該函數(shù)中,您可以通過this
. 那時(shí),一些屬性,例如對應(yīng)于 的屬性,props
將已經(jīng)存在。然而,其他人不會(huì)。
從返回的對象data
用于在實(shí)例上創(chuàng)建新屬性。在這種情況下,您將創(chuàng)建 4 個(gè)屬性:topic1
、topic2
和。Vue 根據(jù)返回的對象創(chuàng)建這些屬性,因此在函數(shù)運(yùn)行之前它們不會(huì)存在。currentBreed
breeds
data
{ name: this.topic1 , key: this.topic1 },
因此,當(dāng)您在該函數(shù)中編寫代碼時(shí),data
您會(huì)嘗試訪問一個(gè)topic1
尚未存在的名為的屬性。因此,它將具有 的值undefined
。因此,您正在創(chuàng)建一個(gè)等效于{ name: undefined , key: undefined },
.
此外,沒有返回的鏈接topic1
。topic1
當(dāng)值更改時(shí),該對象不會(huì)更新。
關(guān)于時(shí)間的幾點(diǎn)也值得注意。
該
data
函數(shù)將在created
鉤子之前調(diào)用,因此在填充屬性axios
之前不會(huì)進(jìn)行調(diào)用。data
axios
調(diào)用是異步的。使用
await
可能會(huì)使代碼更易于閱讀,但“等待”大多只是一種錯(cuò)覺。函數(shù)內(nèi)部的剩余代碼在等待的 promise 解決之前不會(huì)運(yùn)行,但這不會(huì)導(dǎo)致函數(shù)外部的任何內(nèi)容等待。await
相當(dāng)于使用then
.該組件將在
created
調(diào)用鉤子后立即呈現(xiàn)。這是同步的,它不會(huì)等待axios
請求。mounted
然后將在調(diào)用完成之前調(diào)用該鉤子axios
。
所有這一切意味著您可能需要調(diào)整模板以處理axios
調(diào)用尚未完成的情況,因?yàn)樗畛鯐?huì)在值topic1
和topic2
可用之前呈現(xiàn)。
具體解決breeds
您有幾個(gè)選擇的屬性。一種是在值加載后注入值:
breeds: [
{ name: "" , key: "" }, // Initially empty values
{ name: "German Shepherd", key: "germanshepherd" },
// ...
const res = await this.promise;
this.topic1 = res.data[0].Trends;
this.topic2 = res.data[1].Trends;
this.breeds[0].name = this.breeds[0].key = this.topic1;
另一個(gè)是使用一個(gè)computed屬性breeds(你會(huì)從datafor this 中刪除它):
computed: {
breeds () {
return [
{ name: this.topic1 , key: this.topic1 },
{ name: "German Shepherd", key: "germanshepherd" },
{ name: "Husky", key: "husky" },
{ name: "Pug", key: "pug" },
{ name: "(Error)", key: "error" },
]
}
}
當(dāng)我們使用一個(gè)computed屬性時(shí),它會(huì)在topic1更改時(shí)更新,因?yàn)樗且粋€(gè)反應(yīng)性依賴項(xiàng)。
在這種情況下,使用computed屬性可能是最自然的解決方案,但您可以使用其他技巧來使其工作。
例如,您可以為第一個(gè)品種對象中的兩個(gè)屬性使用屬性獲取器(即 JavaScript 屬性獲取器,與 Vue 無關(guān)):
data () {
const vm = this;
return {
topic1: null,
topic2: null,
currentBreed: 0,
breeds: [
{
get name () {
return vm.topic1;
},
get key () {
return vm.topic1;
}
},
{ name: "German Shepherd", key: "germanshepherd" },
{ name: "Husky", key: "husky" },
{ name: "Pug", key: "pug" },
{ name: "(Error)", key: "error" },
]
}
},
我并不是在為您的用例提倡這種方法,但這是一種有趣的方法,有時(shí)可能很有用。topic1需要注意的關(guān)鍵是如何僅在訪問屬性時(shí)評估依賴關(guān)系,name而key不是在data執(zhí)行函數(shù)時(shí)。這允許topic1注冊為任何正在訪問的依賴項(xiàng)name,key例如在渲染期間。
添加回答
舉報(bào)