无法访问商店模块中的吸气剂

can't access getters in store module

这是我的商店模块的定义。

// 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
};

以上是我的 user-store 模块,我收到了 Uncaught TypeError: getters.getName is not a function 错误。当我更改代码以使用访问 state 而不是 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 {
}

问题

这是你的错误:

Uncaught TypeError: getters.getName is not a function

这是您的代码:

getFullName: (state, getters) => {
  return `${getters.getName()} ${getters.getLastName()}`;
},

抛出错误是因为您试图将 getters.getName 作为函数 (getters.getName()) 调用,但它不是函数。

您可以将其与报告没有抛出错误的情况进行比较:

getFullName: (state, getters) => {
  return `${state.current.name} ${state.current.lastName}`;
},

您正在以 属性 的形式访问 state.current.name – 而不是将其作为函数调用。

有关使用 getter 的指南,请参阅 Vuex 的 getter documentation

解决方案

通过删除不需要的括号,停止尝试将 getters.getName 作为函数调用。

备注

为什么 getters.getName 不是函数?看起来像是将其定义为一个函数。看看文档中的这个例子——doneTodos 是一个函数,对吧?

getters: {
  doneTodos: state => {
    return state.todos.filter(todo => todo.done)
  }
}

https://vuex.vuejs.org/en/getters.html

您在 getters 对象上定义的方法被设置为存储对象的 getter。 Getter 允许您访问动态计算的值,就好像它们是 属性(即没有函数调用)。

Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter. It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

有关 getter 的定义和使用方式,请参阅 MDN doc

VueJS 把你在 getters 对象上定义的方法并使用 Object.defineProperty to define getters on the store object which in turn lets you access dynamically computed properties. If you are familiar with VueJS's computed properties,行为和用法基本相同。

进一步阅读