Using Vuex in Vue applications is a very common operation. However, occasionally when using Vuex, you will encounter the error message "TypeError: Cannot read property 'xxx' of undefined". This error message means that the undefined property "xxx" cannot be read, resulting in program errors. The reason for this problem is actually obvious, because when calling a certain property of Vuex, this property is not initialized correctly.
The solution to this problem is also very simple. Typically, this error is caused by the Vuex value not being initialized correctly, so we need to initialize the variable. The following are two examples:
1. Use VueX in the component
<template> <div> <p>{{ name }}</p> </div> </template> <script> import { mapState } from 'vuex'; export default { computed: { ...mapState(['name']) } } </script>
If we use the above code in the code, but the "name" attribute is not defined in the Vuex Store, Then an error will be reported: "TypeError: Cannot read property 'name' of undefined." In order to solve this problem, we only need to add the name attribute to the Vuex Store and initialize it.
2. Initialize variables in Vuex Store
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { name: '' // 需要先进行初始化 }, mutations: { SET_NAME(state, name) { //进行更改,并重新赋值 state.name = name } }, actions: { setName({commit}, name) { //dispatch对应的方法 commit('SET_NAME', name) } }, getters: { name: (state) => { return state.name //getters同样需要返回一个指定的属性 } } }) export default store
In the above code, we initialize the "name" attribute that only declares an empty string. In this way, the error "TypeError: Cannot read property 'name' of undefined" will not appear when calling.
To summarize, this error is very common, but it is also very simple to solve. You only need to properly initialize the Vuex variables in the application. This way we can get the correct values and use Vuex better.
The above is the detailed content of How to solve the problem 'TypeError: Cannot read property 'xxx' of undefined' when using vuex in Vue application?. For more information, please follow other related articles on the PHP Chinese website!