vue.js - TypeError:无法读取未定义的属性(读取“产品”)
问题描述
我正在尝试获取产品,然后检查产品 pId 是否在数组中,如果是则过滤。当我软刷新“TypeError:无法读取未定义的属性”(读取“产品”)时出现错误,几乎就像当计算试图获取数据时我的“this.products”尚未填充一样。尝试添加一些 if 语句来检查数据,但没有运气。
<script>
export default {
data() {
return {
popular_products: [],
products: [],
}
},
computed: {
bestsellers() {
const keywords = this.popular_products
let array = []
for (var index = 0; index < keywords.length; index++) {
const keyword = this.products.data.products.product.filter(
(product) => product.pId == keywords[index].ProductNumber
)
array = array.concat(keyword)
}
return array
},
},
mounted() {
axios
.get(
'https://myurl/admin/api/collections/get/popularproducts?token=account-9306f9192049d3c442e565f2de5372'
)
.then((response) => (this.popular_products = response.data.entries))
axios
.get('https://myurl/products.json')
.then((response) => (this.products = response))
},
}
</script>
解决方案
问题在于这一行:
let keyword = this.products.data.products.product.filter(product => product.pId == keywords[index].ProductNumber);
更具体的阅读:data.products
。
您会看到,在您的呼叫完成之前评估computed
属性。bestsellers
axios
因此,Vue 无法找到products
,data
因为您this.products
没有data
密钥。
最好的解决方案是更改此分配:
- .then(response => (this.products = response)); // delete this line
+ .then(response => (this.products = response.data.products)); // add this line
评论后更新。
if (this.products.product) {
return this.products.product.filter(...)
} else {
return []
}
推荐阅读
- android - 如何在 Jetpack Compose 中创建自定义 TextField
- c++ - 如何使用 C++ 接受套接字中的并发请求
- database - 个性化应用中每个用户的授权
- php - 在单独的函数php中获取函数中更新的全局变量的值
- javascript - 在 vscode 中遵循 json 模式引用 ($ref) 链接时转到文件
- javascript - Reactjs 中的 Axios 和 fetch 都在发出持续的 localhost 网络请求
- android - 如何在 lambda 中返回一个变量
- javascript - NODEJS 中大型 Keep-Alive 的副作用是什么
- laravel - 使用 laravel 工厂制作独特的行
- android - 如何修复无法下载 Android 插件组件:layoutlib-resources:检查日志以获取详细信息错误消息(使用 IntelliJ IDE 社区版)