You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt/Vuex调用getters报Cannot read properties of undefined错误如何解决

问题原因

你当前代码存在2个错误:

    1. 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 读取属性的错误。
    1. 模板v-for迭代变量名不匹配
      你在模板里写的是 v-for="yellow in yellowFruit",但渲染时用的是 {{ fruit.name }},迭代的变量名是yellow而非fruit,就算getter调用正常也会报错,同时对象不能直接作为v-for的key值,建议用唯一属性作为key。

修正后的代码

页面组件代码

<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:24:02