Typescript can';t访问存储模块中的getter
这是my store模块的定义Typescript can';t访问存储模块中的getter,typescript,vue.js,vuejs2,store,vuex,Typescript,Vue.js,Vuejs2,Store,Vuex,这是my store模块的定义 // rest defined above const _GETTERS = { getName: state => { return state.current.name; }, getLastName: state => { return state.current.lastName; }, getFullName: (state, getters) => { // return `${state.
// rest defined above
const _GETTERS = {
getName: state => {
return state.current.name;
},
getLastName: state => {
return state.current.lastName;
},
getFullName: (state, getters) => {
// return `${state.current.name} ${state.current.lastName}`;
return `${getters.getName()} ${getters.getLastName()}`;
},
getMailAddress: state => {
return state.current.mailAddress;
}
};
const UsersStore = {
...
getters: _GETTERS
};
上面是我的用户存储
模块,我得到了一个未捕获的TypeError:getters.getName不是一个函数
错误。当我将代码更改为使用访问状态的版本而不是getters
时,一切正常。下面是主存储对象,我将上面的内容作为一个模块添加到其中
export default new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: _state,
getters: _getters,
actions: _actions,
mutations: _mutations,
modules: {
users: UserStore
}
});
这是应该呈现它的地方,当直接访问存储而不是使用getter时,它工作得很好
import {Component, Vue} from 'vue-property-decorator';
import {mapGetters} from 'vuex';
const template = require('./app-footer.vue').default;
@Component({
mixins: [template],
computed: {
...mapGetters({
name: 'getFullName'
})
}
})
export default class AppFooter extends Vue {
}
问题
以下是您的错误:
未捕获类型错误:getters.getName不是函数
这是您的代码:
引发此错误的原因是,您试图将getters.getName
作为函数(getters.getName()
)调用,而它不是函数
您可以将其与报告没有抛出错误的情况进行比较:
您正在作为属性访问state.current.name
,而不是将其作为函数调用
有关使用getter的指导,请参阅Vuex
解决方案
通过删除不需要的括号,停止尝试将getters.getName
作为函数调用
笔记
为什么getters.getName
不是函数?它看起来像是定义为一个函数。看看文档中的这个例子–doneTodos
是一个函数,对吗?
–
在getters
对象上定义的方法被设置为存储对象上的gettersgetter允许您访问动态计算的值,就像它们是属性一样(即不需要函数调用)。
有时,允许访问返回动态计算值的属性是可取的,或者您可能希望在不需要使用显式方法调用的情况下反映内部变量的状态。在JavaScript中,这可以通过使用getter来实现。虽然可以结合使用getter和setter来创建伪属性类型,但不可能同时将getter绑定到属性并使该属性实际持有值
–
有关如何定义和使用getter的信息,请参见
VueJS接受在getters
对象上定义的方法,并用于在store对象上定义getters,从而允许您访问动态计算的属性。如果您熟悉VueJS,其行为和用法基本相同
进一步阅读
Hm我以前测试过,但由于某种原因它不起作用。。也许我当时还有另一个问题——你显然是对的。那么它又怎么不是一个函数呢?当我有一个引用匿名函数的对象属性时,我总是像函数一样“调用”该属性。@MJB:我已经编辑了我的答案,以便在您的评论中涵盖这个问题。
getFullName: (state, getters) => {
return `${getters.getName()} ${getters.getLastName()}`;
},
getFullName: (state, getters) => {
return `${state.current.name} ${state.current.lastName}`;
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}