【问题标题】:What is the correct way to use component props in a Vuex getter?在 Vuex getter 中使用组件道具的正确方法是什么?
【发布时间】:2016-11-21 03:16:07
【问题描述】:

假设您有一个简单的应用程序组件,其中包含一个按钮,可以使用 vuex 商店从计数器组件中添加多个计数器。

Here is the whole thing on webpackbin.

有点像vuex git repo中的基本反例。但是你想使用带有通过组件上的属性传递的ID的vuex getter,你会怎么做?

getter 必须是纯函数,所以不能使用this.counterId。官方文档说您必须使用计算属性,但这似乎也不起作用。此代码为 getter 返回 undefined:

import * as actions from './actions'

export default {
    props: ['counterId'],
    vuex: {
        getters: {
            count: state => state.counters[getId]
        },
        actions: actions
    },
    computed: {
        getId() { return this.counterId }
    },
}

【问题讨论】:

  • 您的代码似乎是正确的。 “getId”计算属性背后的想法是让您使用组件中的属性,而不是状态。在你的情况下,你正在做这两件事。没有错,但在调用 getId() 时要注意你的逻辑以及从中得到什么。
  • id 只是数组索引。计算属性本身工作正常。尽管 getter 仍然返回 undefined ,所以一定有问题。我正在使用计算属性,因为根据定义,您不能在 getter 中使用 this

标签: javascript vue.js vuex


【解决方案1】:

getter 应该是纯函数,不依赖于组件状态。

你仍然可以从 getter 中创建一个计算出来的 prop,或者直接使用 store:

//option A
export default {
    props: ['counterId'],
    vuex: {
        getters: {
            counters: state => state.counters
        },
        actions: actions
    },
    computed: {
        currentCounter() { return this.counters[this.counterId] }
    },
}

//option B (better suited for this simple scenario)
import store from '../store'
computed: {
  currentCounter() {  
    return store.state.counters[this.counterId] 
  }
}

【讨论】:

  • 在 webpackbin 上添加了两个版本 Version A - Version B 通常它可以工作,但突变不会更新计数器。我可以将计数器递增几次,并且只有在使用 AddCounter 函数添加新计数器时才会更新。
  • 那是你的突变的问题。您使用 Vue 无法检测到的 state.counter[counterId]++ 增加了值 (vuejs.org/guide/list.html#Caveats)。我改用 .splice() 并且它可以工作:webpackbin.com/Vy_BMMIwZ(还更改了 Couter.vue 以接收计数器)
  • 好吧,明白了,你是对的。我忘了使用 state.counters.$set(counterId, state.counters[counterId] + 1) 而不是存储对象中的 ++ 突变 ...
猜你喜欢
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 2022-01-25
  • 2023-01-13
  • 1970-01-01
  • 2021-08-08
  • 2018-05-29
相关资源
最近更新 更多