关于在使用Vuex时终端报错TypeError: Cannot read properties of undefined (reading ‘state‘)的解决方案

下面都是代码的正确语法书写和使用,先和自己的代码对一下,没有语法错误在看后面的解决方案。

1.当创建一个vue2项目后并安装最新的vuex包(没有指定版本)

2.引入vuex并生成一个store对象(src/store/index.js)

import Vue from "vue"
// 1.安装vuex包
// 2.导入vuex
import Vuex from 'vuex'
// 3. 把vuex注册为vue的插件
// 在vue实例的原型上挂载一个$store属性
Vue.use(Vuex)
// 4.定义规则并生成store对象
const store = new Vuex.Store({
  state: {
    count: 100
  }
  
})

// 5.导出到main.js中 注册到 new Vue 中
export default store

3.在main.js中挂载store(src/main.js)

import Vue from 'vue'
import App from './App.vue'
import store from '@/store/index.js'
Vue.config.productionTip = false

new Vue({
  // 让Vue项目有vuex的功能
  // 给Vue实例的原型上的$store赋值(值为store中的state)
  store,
  render: h => h(App),
}).$mount('#app')

4.到这里为止都是vuex正确的使用但是终端还是报错TypeError: Cannot read properties of undefined (reading ‘state‘)

报错原因:vue2的版本和vuex的版本不匹配导致的,我们的代码书写是没有问题的。

解决方案:安装指定的vue和vuex的版本就可以了。

猜你喜欢

转载自blog.csdn.net/qq_71247851/article/details/126993574