首页 > 解决方案 > 尝试在 vue3 + vuex4 + typescript 中使用 $store.getters 时无法读取未定义的属性

问题描述

我有一个使用 vue 3、vuex 4 和 typescript 的项目。在这个项目中,我有一个名为getColor1

export const getters: GetterTree<AnimationCanvasState, RootState> = {
  getFrames(state): Array<Frame> {
    return state.frames
  },
  getColor1(state): number {
    return state.color1
  },
}

getter 被导入到模块的状态中:

import { Module } from 'vuex'
import { RootState } from '../../types'
import { getters } from './getters'
...
import { AnimationCanvasState } from './types'

const state: AnimationCanvasState = {
  color1: 0,
...
}

export const animationCanvas: Module<AnimationCanvasState, RootState> = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}

依次导入根存储:

import { createStore, StoreOptions } from 'vuex'
import { RootState } from './types'
import { animationCanvas } from '@/store/modules/animation-canvas'

const store: StoreOptions<RootState> = {
  modules: {
    animationCanvas,
  },
}

export default createStore(store)

我遇到的问题是,如果我尝试通过this.$store...计算属性中的方法引用 getter:

computed: {
    color1: {
        get(): number {
            return this.$store.getters.animationCanvas.getColor1;
        },
        set(value) {},
    },
},

我得到错误:

无法读取未定义的属性“getColor1”

在此处输入图像描述

问题是,如果我使用该mapGetters工具,getColor1getter 工作正常:

computed: {
    ...mapGetters('animationCanvas', ['getColor1']),
    color1: {
        get(): number {
            return this.getColor1;
        },
        set(value) {},
    },
},

在此处输入图像描述

更奇怪的是,如果我在计算属性的 get 中停止我的代码并在控制台中手动钻取 getter,我可以看到getColor1 getter 以及this.$store.getters对象中的所有其他命名空间的 getter,但是当我尝试访问他们我得到一个错误:

在此处输入图像描述

我知道我可以只使用 mapGetters,但我一直遇到这样的小问题,这让我觉得我的设置有问题。

有谁知道为什么会这样?

更新

当我回顾我的问题时,我意识到使用 this.$store 方法,命名空间和 getter 是一个单一的属性值,我将其与结构化路径混为一谈。如果我对属性使用密钥访问方法,它可以工作:

this.$store.getters['animationCanvas/getColor1']

在此处输入图像描述

但这就是命名空间模块在 vuex 中的工作方式吗?

标签: typescriptvuexstorevuejs3

解决方案


推荐阅读