【问题标题】:Get and edit state from a component using Vuex. ReferenceError: $store is not defined使用 Vuex 从组件获取和编辑状态。 ReferenceError: $store 未定义
【发布时间】:2020-04-08 12:06:27
【问题描述】:

我正在使用 Vuex 来存储一些数据。我正在尝试获取存储在 state 中的值,但我不知道如何从组件中检索它。

我想从如下所示的组件中加载 data 函数中的值。我可以使用this.$store.dispatch('currentUser/loginUser',this.user)成功保存一些数据,但我不知道如何获取。

这是 Vuex 模块的结构:

我要获取的数据在 loginSettings.js 文件中。我需要检索 closed 布尔值。这是文件里面的内容:

const state = {
    loginModal:{
        closed: false, // This is the value I need
    }
};
const getters = {};
const actions = {};
const mutations = {};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}

这是我组件中的脚本标签。

<script>
  export default {
    data: () => ({
      dialog: this.$store.state.loginModal.closed, // This is throwing an error. The error is under this code block
      user:{
          email: "",
          password: ""
      }
    }),
    methods:{
        login(){
            this.$store.dispatch('currentUser/loginUser',this.user)
        }
    }

  }
</script>

错误:Error in data(): "ReferenceError: $store is not defined"

使用 Vuex 使组件的属性反应的正确方法是什么?

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    您忘记了this,因此它不是在 Vue 实例上查找 $store 变量,而是在全局范围内查找 $store 变量(未定义)。此外,对于命名空间模块,您需要在 this.$store.state 之后包含模块名称,因此 this.$store.state.loginSettings 是您尝试访问的状态对象。

    但是,您希望将存储变量放在计算变量中,而不是数据中,以便它们在更改时进行更新。数据只是本地状态,因此它只会最初将您的本地状态设置为您的 vuex 存储中的状态,而不是响应式的。

    因此,这应该是你的答案:

    computed: {
      loginModal() {
        return this.$store.state.loginSettings.loginModal
      }
    }
    
    // or
    
    computed: {
      closed() {
        return this.$store.state.loginSettings.loginModal.closed
      }
    }
    

    我建议不要将本地状态(组件是否已关闭或似乎不是特定于该组件)放在您的 vuex 存储中。

    附:您可以import { mapState } from 'vuex' 并使用它为您自动生成计算属性,如下所示:

    computed: {
      ...mapState('loginSettings', ['loginModal']),
    }
    

    【讨论】:

    • 对不起,我忘记了帖子中的this,但我添加了它,我遇到了同样的错误。 $store 未定义。我正在使用data,因为该组件是一个 Vuetify 组件。我刚刚按照您所说的方式设置了一个计算属性并且它正在工作,但是我需要将值传递给数据,我该怎么做?
    • 哪个 Vuetify 组件?计算属性的分配方式与数据属性相同。
    • 一个对话框组件。我不知道这是可能的!谢谢!
    【解决方案2】:

    将state 值直接分配给data 将引发错误。您可以改为在 computed 中调用它。

    computed:{
      dialog:function(){
        return this.$store.state.loginModal.closed;
      }
    }
    

    【讨论】:

    • 那么将值分配给data 的正确方法是什么?这是一个 Vuetify 组件,所以值需要在data
    • computed 中的函数将与data 一样工作。之前没试过vuetify,请问vuetify中用计算出的函数名代替data可以吗?
    • 抛出这个Error in render: "TypeError: Cannot read property 'closed' of undefined"
    • 已解决return this.$store.state.loginSettings.loginModal.closed
    • 这可能不是计算部分的问题。你能仔细检查一下存储值和路径吗?
    猜你喜欢
    • 2019-03-21
    • 2020-09-10
    • 1970-01-01
    • 2018-08-01
    • 2018-07-25
    • 2019-12-29
    • 2018-08-09
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多