Nuxt/Vuex调用getters报Cannot read properties of undefined错误如何解决
问题原因
你当前代码存在2个错误:
- Vuex getter 访问方式错误
Vuex 模块化场景下,getter 不会以模块名作为属性嵌套在$store.getters下:
- 若你的
fruits模块未开启命名空间:getter 直接挂载到全局,访问路径为this.$store.getters.getYellowFruit - 若你的
fruits模块开启了namespaced: true:需要通过命名空间路径访问,写法为this.$store.getters['fruits/getYellowFruit']
你之前写的this.$store.getters.fruits.getYellowFruit中,$store.getters.fruits本身不存在,所以抛出 undefined 读取属性的错误。
- Vuex getter 访问方式错误
- 模板v-for迭代变量名不匹配
你在模板里写的是v-for="yellow in yellowFruit",但渲染时用的是{{ fruit.name }},迭代的变量名是yellow而非fruit,就算getter调用正常也会报错,同时对象不能直接作为v-for的key值,建议用唯一属性作为key。
- 模板v-for迭代变量名不匹配
修正后的代码
页面组件代码
<template> <div class="getters-page"> <div class="container text-white"> <ul class="w-2/4 pt-10"> <!-- 修正变量名和key规则 --> <li v-for="yellow in yellowFruit" :key="yellow.name"> {{ yellow.name }} </li> </ul> </div> </div> </template> <script> export default { data() { return {} }, computed: { yellowFruit() { // 未开命名空间用这个 return this.$store.getters.getYellowFruit // 如果fruits模块开了namespaced: true就换成下面这行 // return this.$store.getters['fruits/getYellowFruit'] }, }, } </script>
(可选)开启fruits模块命名空间避免全局命名冲突,修改fruits.js代码如下:
// 新增命名空间配置 export const namespaced = true export const state = () => ({ fruits: [ { name: 'Apple', color: 'red' }, { name: 'Orange', color: 'orange' }, { name: 'Pineapple', color: 'yellow' }, { name: 'Kiwi', color: 'green' }, { name: 'Grapes', color: 'purple' }, { name: 'Banana', color: 'yellow' }, ], }) export const mutations = {} export const actions = {} export const getters = { getYellowFruit: (state) => { return state.fruits.filter((fruit) => fruit.color === 'yellow') }, }
内容的提问来源于stack exchange,提问作者hendy0817
相关产品推荐
相关产品推荐

