typescript - 尝试在 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
工具,getColor1
getter 工作正常:
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 中的工作方式吗?
解决方案
推荐阅读
- regex - 正则表达式找不到所有故障的存在
- android - 将android应用程序中布局的背景颜色与kotlin进行比较
- java - Java 中的更多语法
- java - 如何调用我的音乐课并在 while 循环内播放音乐,该循环在调用音乐课的行下执行我的行?
- c# - 在 Castle Windsor 中使用 XML 配置注册具有多个泛型类型的接口
- javascript - 覆盖 Object.prototype.get 以防止大型应用程序中的空检查问题
- php - PHP PEAR MAIL,如何发送 Outlook 日历邀请?
- ios - css var 中的相对 URL 在 iOS 上工作错误
- javascript - 为什么onclick在javascript中没有点击就执行?
- windows - 如何在 Windows 10 命令行上使用多个 .exe 版本?