【问题标题】:Vuex mapstate undefindedVuex mapstate 未定义
【发布时间】:2020-05-22 12:44:28
【问题描述】:

我在使用 Vuex 地图状态时遇到问题。在测试编写 this.$store.state.count 但我试图将名称缩短为 this.count。我的 vue 项目嵌套很深,所以我尽量缩短变量,并尽量避免在每个组件中使用“计算”​​和其他函数。

我的代码

const store = new Vuex.Store({
    state: {
        count: 43,
    }

});
import { mapState } from 'vuex';


let app = new Vue({
    el: '#app',
    router: new VueRouter(routes),
    store,
    computed: mapState([
        'count'
    ]),
    data: {
        current_path: '/dashboard',
    },
});

我也试过了:

computed: mapState({
    // arrow functions can make the code very succinct!
    count: state => state.count,

    // passing the string value 'count' is same as `state => state.count`
    countAlias: 'count',

    // to access local state with `this`, a normal function must be used
    countPlusLocalState (state) {
      return state.count;
    }
  })

但在我的组件中:当我在 html 中使用 this.count 或 {{count}}(或 countAlias、countPlusLocalState 等)时,它返回 null/undefined。它仅适用于完整参考:this.$store.state.count。

我错过了什么?

【问题讨论】:

  • 你确定商店中count的值不是未定义的吗?
  • @Seblor,是的,因为 this.$store.state.count 返回 43
  • 试试global mixin
  • @DelenaMalan 谢谢!将计算结果放入 mixin 就可以了!如果您将其发布为答案,我会接受!

标签: vue.js vue-component vuex


【解决方案1】:

您可以像这样使用global mixin

Vue.mixin({
    computed: mapState([
        'count'
    ]),
})

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 2021-03-05
    • 1970-01-01
    • 2019-09-25
    • 2018-11-04
    • 2021-11-05
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多