【发布时间】: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