Vue不能读取对象属性的undefined属性,只能在模板中读取



我在value中创建了一个变量

data() {
return {
plans: [],
}

之后给Plans推送对象。当我在js中打印这个对象时,它给出了{id: 'filler', name: 'Premium', priceId: 'filler', price: '10000'}。我也可以用console.log(this.plans[1]['name'])来获取名称,它会正确显示"Premium"。然而,在模板中,我试图用<h1>{{plans[0].name}}</h1>显示名称(我也尝试过作为['name']),它说未捕获(在承诺中)TypeError:无法读取未定义的属性(读取'name')。然而,如果我只给它<h1>{{plans[0]}}</h1>,它会正确地显示整个对象。我很困惑我错过了什么,如果需要更多的信息,请告诉我。

编辑:用以下

填充数组
async getPlans(){

const db = getFirestore()
const productsRef = collection(db, "products")
const productsQuery = query(productsRef, where("active","==", true))
const productsQuerySnap = await getDocs(productsQuery)
// console.log(productsQuerySnap[0])
// const temp = []
for (let i = 0; i<2; i++){
// const doc = i.docs
console.log(productsQuerySnap.docs[i])
const pricesRef = collection(db, "products", productsQuerySnap.docs[i].id, "prices")
const pricesQuerySnap = await getDocs(pricesRef)
const name = productsQuerySnap.docs[i]["_document"]["data"]["value"]["mapValue"]["fields"]["name"]["stringValue"]
console.log(pricesQuerySnap.docs[0]["id"])
const priceId = pricesQuerySnap.docs[0]["id"]
const price = pricesQuerySnap.docs[0]["_document"]["data"]["value"]["mapValue"]["fields"]["unit_amount"]['integerValue']
console.log({id: productsQuerySnap.docs[i].id, name: name, priceId: priceId, price: price})
this.plans.push({id: productsQuerySnap.docs[i].id, name: name, priceId: priceId, price: price})
}
console.log(this.plans[0]['name'], "plans is running")

},

它在挂载

中运行

在访问模板中的数据之前,一定要确保数据是可用的。这些类型的错误(不能读取属性未定义的…)主要是由于缺乏先检查。

在您的例子中,在访问plans arrayplans' key (plans[0])之前,创建一个计算属性或直接在模板中应用一个条件来检查它是否在DOM中可用,就像这样-

  1. 如果你想循环所有的计划项目-
<template>
<div v-if="plans && plans.length">
<template v-for="(item, index) in plans">
<h1>{{ item.name }}</h1>
</template>
</div>
</template>
  1. 如果您只想显示单个项目-
<template>
<div v-if="plans && plans.length && plans[0]">
<h1>{{ plans[0].name }}</h1>
</div>
</template>

推荐-

不需要直接在模板中编写plans && plans.length,您可以为它创建一个computed属性,并且无需重复代码即可访问任何地方-

<template>
<div v-if="isPlansAvailable">
<template v-for="(item, index) in plans">
<h1>{{ item.name }}</h1>
</template>
</div>
</template>
<script>
export default {
name: "ComponentName",

data() {
return {
plans: [],
}
},

computed: {
isPlansAvailable() {
return this.plans && this.plans.length;
}
},

mounted() {
// YOUR API METHOD
},
}
</script>
data() {
return {
plans: Object,
}

我不确定是否有利用方法和mounted的解决方案,但我通过使用setup()而不是方法和mounted解决了这个问题。我将ref的值设置为完整的对象数组,然后在设置结束时返回值,然后在模板中正确访问所有内容。

相关内容

最新更新