Ric*_*old 5 vue.js vue-component vuex
当我把它放在我的 Vue 组件中时......
// using store getter
computed: {
authenticated() {
return this.$store.getters.authenticated
}
}
Run Code Online (Sandbox Code Playgroud)
... 有用。的值authenticated是响应式的,true当 vuex 存储中的值为 时,计算属性返回true。
这应该有效......(并且根据文档将是正确的方法)
// using store state
computed: {
authenticated() {
return this.$store.state.authenticated
}
}
Run Code Online (Sandbox Code Playgroud)
......但没有。计算属性始终为false。
它甚至不适用于初始状态,所以我猜它与动作或突变无关。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
}
};
Run Code Online (Sandbox Code Playgroud)
因此,它适用于商店 getter,但不适用于商店状态。Afaik 商店状态也应该是被动的。
知道我可能做错了什么吗?
假设您按照我下面的方式构建 Vuex.Store,则使用 或 计算得出的结果将按预期state.authenticated工作getters.authenticated。
突变部分没有什么区别,所以我把它拿出来,让事情变得最小。
正如 Bert 指出的,你的 getter 应该state作为参数;否则,它使用的是声明的const,在本例中是相同的,但读起来具有欺骗性。
const authenticate = {
isAuthenticated() {
return true;
}
};
const state = {
authenticated: authenticate.isAuthenticated()
};
const getters = {
authenticated (state) {
return state.authenticated;
}
};
const store = new Vuex.Store({
state,
getters
});
new Vue({
el: '#app',
store,
computed: {
authenticated() {
return this.$store.state.authenticated;
}
}
});Run Code Online (Sandbox Code Playgroud)
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<script src="//unpkg.com/vuex@latest/dist/vuex.js"></script>
<div id="app">
Anything? {{authenticated}}
</div>Run Code Online (Sandbox Code Playgroud)