【问题标题】:Can't access $store when importing Vuex instance from an external file从外部文件导入 Vuex 实例时无法访问 $store
【发布时间】:2023-03-21 18:56:01
【问题描述】:

我正在创建一个counter using Vue & Vuex 2
尝试使用 this.$store.state.count 访问 store 对象上的 count 属性时,我收到 Cannot read property 'state' of undefined 错误。

当我在main.js 中创建商店实例而不是导入它时,错误没有 出现并且一切正常。

ma​​in.js

import Vue from 'vue'
import Vuex from 'Vuex'
import App from './App.vue'
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 default new Vuex.Store({
  state: {
    count: 1
  }
});

Counter.vue

export default {
  name: 'counter',
  template: `<span>{{ count }}</span>`,
  computed: {
    count () {
        return this.$store.state.count
    }
  },
}

知道商店导入有什么问题吗?

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    你以不同的方式导入了 vue:

    import Vue from 'Vue'
    

    store.js

    import Vue from 'vue'
    

    main.js

    更改您的 store.js 导入以匹配 main.js 以解决问题,即

    import Vue from 'vue'
    import Vuex from 'Vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
        count: 1
      }
    });
    

    您还可以在 main.js 中删除 Vuex 导入

    【讨论】:

    • 在为 Vue 项目切换打包器时我自己也遇到了类似的问题,就是商店的文件正在导入 Vue 的 vue/dist/vue 模块?
    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 2019-12-06
    • 2019-04-05
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2021-07-26
    相关资源
    最近更新 更多