Regarding the solution to the error TypeError: Cannot read properties of undefined (reading 'state') reported by the terminal when using Vuex

The following are the correct syntax for writing and using the code. Check it with your own code first. If there are no syntax errors, look for the solution later.

1. After creating a vue2 project and installing the latest vuex package (no version specified)

2. Introduce vuex and generate a store object (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. Mount store(src/main.js) in 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. So far, vuex has been used correctly, but the terminal still reports an error TypeError: Cannot read properties of undefined (reading 'state')

Reason for the error: The version of vue2 does not match the version of vuex. There is no problem with our code writing.

Solution: Just install the specified versions of vue and vuex.

Guess you like

Origin blog.csdn.net/qq_71247851/article/details/126993574