【问题标题】:Vuex $state issueVuex $state 问题
【发布时间】:2017-06-10 14:21:27
【问题描述】:

我有这样的错误: 我之前认为这是路由器的问题,但是在创建只有 vuex 问题的新项目后仍然存在

enter image description here

这是我的 main.js

import Vue from 'vue'
import App from './App'
import store from './store'

new Vue({
  el: "#app",
  store,
  render: h => h(App)
})

store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    users: [
      {id: 1, name: 'Adrian', email: 'adrian@email.pl'},
      {id: 2, name: 'Magda', email: 'magda@email.pl'}
    ]
  }
})

和我使用 $store 的组件:

<template>
  <div class="usersNames">
    <ul>
      <li v-for="user in usersNames">{{user.name}}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: 'usersNames',
    computed: {
      usersNames() {
        return this.$store.state.users;
      }
    }
  }
</script>

【问题讨论】:

  • 你的例子应该可以工作jsbin.com/hiduzinadu/edit?html,js,output
  • 所以这可能是节点或某些包的问题。
  • 这很难说,因为您发布的代码实际上是工作代码。
  • 我不认为问题出在节点或其他包上。根据错误信息,我认为其他组件中存在一些错误。
  • 只有一个其他组件基本上什么都不做。

标签: vue.js state vuex


【解决方案1】:

您的示例看起来应该可行,但我想提供一种不同的策略,我认为这将是一种改进,也应该可以解决您的问题。

在您的商店中为您尝试在组件中访问的数据创建一个 getter。

所以把你的商店改成这样:

 import Vue from 'vue'
 import Vuex from 'vuex'

  Vue.use(Vuex)

  export const store = new Vuex.Store({
    state: {
      users: [
       {id: 1, name: 'Adrian', email: 'adrian@email.pl'},
       {id: 2, name: 'Magda', email: 'magda@email.pl'}
      ]
    },
    getters:{
      users: state => return state.users
    }
  });

然后,在您的组件中,使用该 getter 来获取您的用户。

<script>
 export default {
    name: 'usersNames',
    computed: {
     usersNames() {
       return this.$store.getters.users
    }
   }
 }
</script>

【讨论】:

  • 我使用了 getter,但现在我的错误是:Uncaught TypeError: Cannot read property 'getters' of undefined at VueComponent.usersNames (eval at &lt;anonymous&gt; (app.js:672), &lt;anonymous&gt;:10:28)
  • 听起来你的 vuex 存储没有正确初始化。这就是为什么 getter 和直接调用 state 不起作用的原因。确保 Vue.use(vuex) 在正确的位置,或者您的商店未在根 Vue 实例中正确初始化.....我知道它在您发布的代码中,但这可能是根本问题。注销组件中的this.$store 会发生什么?您看到商店的实例了吗?
  • this.$store 返回:'undefined' ;/
  • 完全正确...您的商店没有使用 Vue 根实例正确初始化,所以这就是 getter(或与您的商店相关的任何其他内容)无法正常工作的原因。如果您觉得它正在被初始化,请尝试在您的根 Vue 实例中注销 this.$store...如果它仍然未定义,您知道这是一个初始化问题。
  • 啊,是的。 store 是“命名导入”而不是默认值,因此括号是必要的。很高兴您发现了问题
【解决方案2】:

你可以改变 main.js:import {store} from './store';

【讨论】:

  • 或者修改store.js :export default new Vuex.Store({})
【解决方案3】:

您的 vuex 似乎没有正确注入 vue。

可能与您的问题无关,但只是为了最佳实践,最好使用 mapState 助手;
在您的组件中:

import { mapState } from 'vuex'

export default {
  name: 'usersNames',
  computed: {
    ...mapState({
      usersNames: 'users'
    }),
    yourLocalComputed () {}
  }
}

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 2021-10-19
    • 2021-02-28
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多