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

如何在v-for循环中调用对象属性存储的方法?

解决方案

你当前的问题是模板中绑定的menuItem.function是字符串,而非实际的方法引用,所以无法触发对应methods里的函数。可以通过以下两种方式解决:

方法一:使用通用处理函数(推荐)

修改模板代码

将列表项的点击事件改为调用一个通用方法,并传入方法名称:

<v-list dense>
  <template v-for="(menuItem, index) in menuItems">
    <v-list-item :key="index" @click.stop="handleMenuItemClick(menuItem.function)">
      <v-list-item-icon>
        <v-icon :color="menuItem.color">{{ menuItem.icon }}</v-icon>
      </v-list-item-icon>
      <v-list-item-title> {{ menuItem.title }} </v-list-item-title>
    </v-list-item>
  </template>
</v-list>

在methods中添加通用处理函数

通过实例的属性访问方式this[methodName]获取对应方法并执行,同时增加存在性判断避免报错:

methods: {
    cardClick() {
        this.$nuxt.$emit('set-part', this.tab)
    },
    add() {
        this.$nuxt.$emit('add-part', this.part.PK_R_ASSEMBLY)
    },
    addExisting() {
        this.$nuxt.$emit('add-existing-part', this.part.PK_R_ASSEMBLY)
    },
    disable() {
        this.$nuxt.$emit('disable-part', this.part.PK_R_ASSEMBLY)
    },
    collapse() {
        this.$nuxt.$emit('collapse', this.tab.PK_R_ASSEMBLYDETAILSUBASSEMBLY)
    },
    open() {
        this.$nuxt.$emit('open', this.tab.PK_R_ASSEMBLYDETAILSUBASSEMBLY)
    },
    // 新增通用处理方法
    handleMenuItemClick(methodName) {
        if (typeof this[methodName] === 'function') {
            this[methodName]()
        }
    }
}

方法二:直接在模板中调用(简化版)

如果能确保所有menuItem.function对应的方法都存在,可以直接在模板中通过实例属性访问执行:

<v-list dense>
  <template v-for="(menuItem, index) in menuItems">
    <v-list-item :key="index" @click.stop="this[menuItem.function]()">
      <v-list-item-icon>
        <v-icon :color="menuItem.color">{{ menuItem.icon }}</v-icon>
      </v-list-item-icon>
      <v-list-item-title> {{ menuItem.title }} </v-list-item-title>
    </v-list-item>
  </template>
</v-list>

原理说明

Vue组件的methods会被挂载到组件实例(即this)上,所以可以通过this[方法名称字符串]的方式获取到对应的方法引用,进而调用执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:15:34