【发布时间】:2020-03-25 12:21:47
【问题描述】:
我有一个将状态定义为 null 的 Vuex 商店:
const state = {
Product: null // I could do Product:[] but that causes a nested array of data
};
const getters = {
getProduct: (state) => state.Product
};
const actions = {
loadProduct({commit}, {ProudctID}) {
axios.get(`/api/${ProductID}`).then(response => {commit('setProduct', response.data)})
.catch(function (error) {
//error handler here
}
}
};
const mutations = {
setProduct(state, ProductData) {
state.Product = ProductData
}
};
在我的 Vue 组件中,我想在可用时显示 Product 数据。所以我这样做了:
<template>
<div v-if="Product.length">{{Product}}</div>
</template>
当我运行它时,我得到一个错误提示
Vue 警告:渲染错误:“TypeError:无法读取属性‘长度’ 为空”
好的,所以我尝试了这个,然后什么都不做(不抛出错误并且从不显示数据):
<template>
<div v-if="Product != null && Product.length">{{Product}}</div>
</template>
如果Product 对象数据不为空,那么显示它的正确方法是什么? Product 是一个 JSON 对象,其中填充了来自数据库的数据,如下所示:
[{ "ProductID": 123, "ProductTitle": "Xbox One X Gaming" }]
我的 Vue 组件是这样获取数据的:
computed:
{
Product() {
return this.$store.getters.getProduct
}
}
,
serverPrefetch() {
return this.getProduct();
},
mounted() {
if (this.Product != null || !this.Product.length) {
this.getProduct();
}
},
methods: {
getProduct() {
return this.$store.dispatch('loadProduct')
}
}
如果我查看 Vue 开发工具,事实证明,我的 Vue 组件中的 Product 始终是 null,但在 Vuex 选项卡中,它填充了数据。奇怪吗?
【问题讨论】:
-
填充的
Product状态的值为[...]或{....}? -
就像
[{ "ProductID": 123, "ProductTitle": "Xbox One X Gaming" }] -
在您的模板中,将其保留在 v-if="this.state.Product != null"
-
如何在组件逻辑中恢复该状态?
-
@BoussadjraBrahim 我已经更新了我的帖子,以展示我是如何得到它的。使用 Vue 开发工具检查后,我的 Vue 组件计算的
Product数据似乎始终为空,这可能是问题的原因。发现问题 - 应该是mounted() if (this.Product == null ...)而不是!= null