当我把它放在我的 Vue 组件中时......
// using store getter
computed: {
authenticated() {
return this.$store.getters.authenticated
}
}
... 它有效。 authenticated
的值是响应式的,当 vuex 存储中的值为 true
时,计算属性返回 true
。
这应该可行……(根据文档,这将是正确的方法)
// using store state
computed: {
authenticated() {
return this.$store.state.authenticated
}
}
...但是没有。计算属性始终为 false
。
它甚至对初始状态不起作用,所以我猜它与 Action 或突变无关。 vuex 存储在 state
和 getters
(Firefox Vue DevTools) 中保存正确的值。
我的商店是这样的:
const state = {
authenticated: authenticate.isAuthenticated(),
};
const getters = {
authenticated () {
return state.authenticated
}
};
const mutations = {
isAuthenticated (state, isAuthenticated) {
state.authenticated = isAuthenticated
}
};
因此,它适用于 store getter 但不适用于 store state。 Afaik 商店状态也应该是响应式(Reactive)的。
知道我可能做错了什么吗?
最佳答案
除了这个讨论之外,vuex 还提供了 mapGetters
、mapState
、mapActions
和 mapMutations
辅助函数。
对于 authenticated
getter,您可以将其映射为:
import { mapGetters } from 'vuex
computed: {
...mapGetters({
authenticated: 'authenticated'
})
}
有助于保持您的代码简洁明了,imo。
关于vue.js - Vuex 计算属性仅适用于 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48752801/