问题描述
当我把它放在我的 Vue 组件中时......
When I put this in my Vue component ...
// using store getter
computed: {
authenticated() {
return this.$store.getters.authenticated
}
}
...它有效.authenticated
的值是响应式的,当 vuex 存储中的值为 true
时,计算属性返回 true
.
... it works. The value for authenticated
is reactive and the computed property returns true
when the value in the vuex store is true
.
这应该有效......(并且根据文档是正确的方法)
This should work ... (and would be the right way according to the docs)
// using store state
computed: {
authenticated() {
return this.$store.state.authenticated
}
}
...但没有.计算属性始终为 false
.
... but doesn't. The computed property is always false
.
它甚至不适用于初始状态,所以我猜它与动作或突变无关.vuex 存储在 state
和 getters
(Firefox Vue DevTools) 中保存了正确的值.
It doesn't even work on initial state, so I guess it has nothing to do with the action or mutation. The vuex store holds the correct values in the state
and the getters
(Firefox Vue DevTools).
我的商店看起来像这样:
My store looks like this:
const state = {
authenticated: authenticate.isAuthenticated(),
};
const getters = {
authenticated () {
return state.authenticated
}
};
const mutations = {
isAuthenticated (state, isAuthenticated) {
state.authenticated = isAuthenticated
}
};
因此,它适用于商店 getter,但不适用于商店状态.Afaik 商店状态也应该是反应式的.
So, it works with store getters but not with store state. Afaik the store state should be reactive as well.
知道我做错了什么吗?
推荐答案
除此之外,vuex 还提供了 mapGetters
、mapState
、mapActions
和 mapMutations
辅助函数.
More as an aside to this discussion, vuex offers the mapGetters
, mapState
, mapActions
, and mapMutations
helper functions.
对于 authenticated
getter,您可以将其映射为:
In the case of the authenticated
getter, you would map it like:
import { mapGetters } from 'vuex
computed: {
...mapGetters({
authenticated: 'authenticated'
})
}
有助于保持您的代码简洁明了,imo.
Helps to keep your code clean and concise, imo.
这篇关于Vuex 计算属性仅适用于 getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!