我在 vuex store.js 中创建的 getter 出现错误 [英] A getter I made in vuex store.js is getting errors

查看:49
本文介绍了我在 vuex store.js 中创建的 getter 出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vuejs、vuex 和 vuetify.

I am using vuejs, vuex, and vuetify.

涉及到3个文件,我把重要的部分贴出来.

There are 3 files involved I will post the important parts.

基本上我想显示与路由参数对应的数据.每当我在我的 Product.vue 中使用以下内容

Basically I want to display data corresponding to the route parameter. Whenever I use the following in my Product.vue

<h1 class="heading primary--text"> {{ product.partNumber }}</h1>

该文件上没有任何内容加载,当我检查控制台时,我得到以下信息...

Nothing on that file loads, and when I check the console I get the following...

Chrome:类型错误:无法读取未定义的属性‘查找’"

Chrome: "TypeError: Cannot read property 'find' of undefined"

Firefox:[Vue 警告]:渲染错误:TypeError:state.loadedProducts 未定义"

Firefox: [Vue warn]: Error in render: "TypeError: state.loadedProducts is undefined"

在同一个项目中,我制作了一个 vue 页面,使用 v-for 加载页面上的所有产品,还有一个 getter,就好了.

In this same project I made a vue page that loads all the products on the page using v-for, and one of the getters, just fine.

我真的不确定出了什么问题,请在我的发际线消失之前帮助.

I am really unsure what is wrong, please help before my hairline disappears.

store.js

   getters:{
    loadedProducts (state) {
      return state.products.sort((productA, productB) => {
        return productA.partNumber > productB.partNumber
      })
    },
    loadedProduct (state) {
      return (productId) => {
        return state.loadedProducts.find((product) => {
          return product.partNumber === productId
        })
      }
    }
  }

router.js

 {
  path: '/product/:id',
  name: 'Product',
  props: true,
  component: Product
  }

Product.vue

Product.vue

<script>
export default {
  name: 'Product',
  props: ['id'],
  computed: {
    product () {
      return this.$store.getters.loadedProduct(this.id)
    }
  }
}
</script>

推荐答案

不要尝试通过 store 访问 loadedProducts,而是通过 getter 本身访问它.getters 上的文档提供了访问其他 getter 的示例通过第二个参数的吸气剂.

Instead of attempting to access the loadedProducts via store, instead access it through the getters themselves. The docs on getters provide an example of accessing other getters within a getter via the second argument.

Getter 也会接收其他 getter 作为第二个参数

Getters will also receive other getters as the 2nd argument

loadedProduct (state, getters) {
  return (productId) => {
    return getters.loadedProducts.find((product) => {
      return product.partNumber === productId
    })
  }
}

确保为商店属性设置合理的默认值,例如 products 的空数组.

Be sure you are setting reasonable defaults for your store properties such as an empty array for products.

希望有帮助!

这篇关于我在 vuex store.js 中创建的 getter 出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆