Vuex计算属性仅适用于getter

时间:2018-02-12 18:08:56

标签: vue.js vue-component vuex

当我把它放在我的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

它甚至不起作用于初始状态,所以我猜它与动作或变异无关。 vuex存储在stategetters(Firefox Vue DevTools)中保存正确的值。

我的商店看起来像这样:

const state = {
    authenticated: authenticate.isAuthenticated(),
};

const getters = {
    authenticated () {
        return state.authenticated
    }
};

const mutations = {
    isAuthenticated (state, isAuthenticated) {
        state.authenticated = isAuthenticated
    }
};

因此,它适用于商店获取者,但不适用于商店状态。 Afaik商店的状态也应该是被动的。

知道我可能做错了吗?

3 个答案:

答案 0 :(得分:3)

除此之外,vuex还提供了mapGettersmapStatemapActionsmapMutations辅助函数。

对于authenticated getter,您可以将其映射为:

import { mapGetters } from 'vuex

computed: {
    ...mapGetters({
        authenticated: 'authenticated'
    })
}

帮助保持代码干净简洁,imo。

答案 1 :(得分:1)

假设你像我下面那样构建你的Vuex.Store,计算的效果与预期一样state.authenticatedgetters.authenticated

突变部分没有任何区别,所以我把它拿出去做的事情很少。

正如Bert所说,你的getter应该以{{1​​}}为参数;否则,它使用声明的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;
    }
  }
});




答案 2 :(得分:0)

const state = {
   authenticated: authenticate.isAuthenticated(),
};

状态是一个对象。对象中的属性正在尝试调用函数的结果。这可能是问题所在,因为它将要求对象调用函数。首先尝试将其设置为固定值,然后在需要时通过调用突变来更改状态值。

您还可以尝试调用js对象函数来调用状态对象内部的authenticate.isAuthenticated()函数。 此处的详细信息:https://www.w3schools.com/js/js_function_call.asp

可能的解决方案:

const state = {
   authenticated: function(){ return authenticate.isAuthenticated() },
};