【问题标题】:How to define an empty Vuex state and then check it is not empty/null in Vue component?如何定义一个空的 Vuex 状态,然后在 Vue 组件中检查它是否为空/null?
【发布时间】: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

标签: vue.js vuex


【解决方案1】:

这是一个使用计算的经典案例:

computed: {
   product() {
     return this.Product || [];
   }
}

【讨论】:

  • || [] 表示该元素将在页面上呈现,即使 Product 尚未填充任何内容。所以,我认为这不是 OP 想要的。
  • 这将允许在模板中做v-if="product.length"
【解决方案2】:

在执行请求时可以在商店功能中查看 考试

const actions = {
     loadProduct({commit}, {ProudctID}) {
if (this.product.length > 0) {// <-- new code
  return this.product // <-- new code
} else { // <-- new code
     // do the http request
     axios.get(`/api/${ProductID}`)
    .then(response => {
    commit('setProduct', response.data)}
    )
     .catch(function (error) {
     //error handler here
     }
   }// <-- new code
   }
};

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2019-09-05
    • 2019-04-07
    相关资源
    最近更新 更多