【问题标题】:Nuxt store getter not working, ID given to payload is not an Integer + Error: [vuex] do not mutate vuex store state outside mutation handlersNuxt 存储 getter 不起作用,赋予有效负载的 ID 不是整数 + 错误:[vuex] 不在突变处理程序之外改变 vuex 存储状态
【发布时间】:2022-01-17 01:06:48
【问题描述】:

我正在尝试制作产品详细信息页面。详细信息页面名为 _id。 打开时,id 将替换为产品 id。打开页面时,状态设置为从 api 获取的数据。

之后,我尝试使用一个计算属性,该属性引用名为 getProduct() 的 getter,有效载荷中的 id 为 (this.$route.params.id)。

这就是我的 _id.vue 的样子:

methods: {
  ...mapActions("products", ["fetchProducts",]),
  ...mapGetters("products", ["getProduct",]),
},
async mounted() {
  this.fetchProducts()
},
computed: {
  product() {
    return this.getProduct(this.$route.params.id)
  }
}

这就是我的名为 products.js 的商店文件的样子:

import axios from "axios"

export const state = () => ({
  producten: []
})

export const mutations = {
  setProducts(state, data) {
    state.producten = data
  }
}

export const getters = {
  getProduct(state, id) {
    console.log(id)
    return state.producten.filter(product => product.id = id)
  }
}

export const actions = {
  async fetchProducts({ commit }) {
    await axios.get('/api/products')
      .then(res => {
        var data = res.data
        commit('setProducts', data)
      })
      .catch(err => console.log(err));
  }
}

有效的是创建状态,但是当我尝试使用 getter 时出现问题。 如您所见,我 console.log() 给它的 id。其中记录了以下内容:

我也收到错误:client.js?06a0:103 错误:[vuex] 不要在突变处理程序之外改变 vuex 存储状态。

据我所知,我没有做什么?

**注意:**这些错误记录的长度与我的状态数组的长度一样多。

【问题讨论】:

    标签: vue.js nuxt.js vuex store getter


    【解决方案1】:

    来自Vuex documentation

    Vuex 允许我们在 store 中定义“getter”。您可以将它们视为商店的计算属性。与计算属性一样,getter 的结果基于其依赖项进行缓存,并且仅在其某些依赖项发生更改时才会重新评估。

    computedgetters 不支持带参数。

    但是有一种方法可以对 getter 进行“方法式访问”:https://vuex.vuejs.org/guide/getters.html#property-style-access

    您还可以通过返回函数将参数传递给 getter。这在您想查询存储中的数组时特别有用:

    getters: {
      // ...
      getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    

    请注意,通过方法访问的 getter 将在您每次调用它们时运行,并且结果不会被缓存。

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 2022-01-09
      • 1970-01-01
      • 2020-03-30
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2019-11-30
      相关资源
      最近更新 更多