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

Vue3如何在v-for循环中使用inject注入的列表数据?

问题原因

你通过provide传递的itemList是Vue.computed返回的Ref对象,inject拿到该Ref后,Vue默认不会在模板中对inject的Ref进行自动解包。此时你直接遍历itemList本质是遍历Ref实例对象,而非内部包裹的数组,自然无法拿到正确的条目对象,访问i.message就会抛出未定义错误。

修复方案

提供两种通用修复方式,任选其一即可:

方案1:模板中显式取Ref的value

直接修改ItemList组件的模板,在遍历前取Ref的value属性拿到实际数组:

const ItemList = {
    inject: ["itemList"],
    template:`<ul>
                  <list-item v-for="(item, index) in itemList.value" :i="item" :idx="index"></list-item>
              </ul>`
}

方案2:组件内通过计算属性解包(更推荐,模板逻辑更干净)

在ItemList组件内新增计算属性解包Ref,模板直接使用计算属性遍历:

const ItemList = {
    inject: ["itemList"],
    computed: {
        validItemList() {
            return this.itemList.value
        }
    },
    template:`<ul>
                  <list-item v-for="(item, index) in validItemList" :i="item" :idx="index"></list-item>
              </ul>`
}

如果你使用的是Vue 3.3及以上版本,也可以在inject配置中开启自动解包,无需修改模板:

const ItemList = {
    inject: {
        itemList: {
            default: () => [],
            unwrap: true
        }
    },
    template:`<ul>
                  <list-item v-for="(item, index) in itemList" :i="item" :idx="index"></list-item>
              </ul>`
}

内容的提问来源于stack exchange,提问作者MikeRand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 03:18:03