当我把它放到我的Vue组件中时...
// using store getter
computed: {
authenticated() {
return this.$store.getters.authenticated
}
}..。它起作用了。authenticated的值是反应性的,当vuex存储中的值为true时,computed属性返回true。
这应该行得通。(根据文档,这将是正确的方式)
// using store state
computed: {
authenticated() {
return this.$store.state.authenticated
}
}..。但不是。计算属性始终为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
}
};因此,它可以与store getter一起工作,但不能与store state一起工作。Afaik存储状态也应该是reactive。
你知道我可能做错了什么吗?
发布于 2018-02-13 07:33:59
顺便说一句,vuex提供了mapGetters、mapState、mapActions和mapMutations助手函数。
在使用authenticated getter的情况下,您将按如下方式映射它:
import { mapGetters } from 'vuex
computed: {
...mapGetters({
authenticated: 'authenticated'
})
}有助于保持代码的整洁和简洁性,imo。
发布于 2018-02-13 02:40:26
假设您像我在下面所做的那样构造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;
}
}
});<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>
发布于 2020-05-23 14:19:22
const state = {
authenticated: authenticate.isAuthenticated(),
};状态是一个对象。对象中的属性正在尝试调用函数的结果。这可能就是问题所在,因为它会要求对象调用函数。首先尝试将其设置为固定值,然后在需要时通过调用突变来更改状态值。
您还可以尝试使用js对象函数调用来调用状态对象中的authenticate.isAuthenticated()函数。详情请访问:https://www.w3schools.com/js/js_function_call.asp
可能的解决方案:
const state = {
authenticated: function(){ return authenticate.isAuthenticated() },
};https://stackoverflow.com/questions/48752801
复制相似问题