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

Vue 3中无this情况下如何动态调用方法?

Vue 3 中实现方法的动态调用

Vue 3 分为两种写法场景,对应不同的动态调用方式:

1. Options API 写法

这种写法和 Vue 2 逻辑一致,依然可以通过 this 来动态调用方法,和你之前的写法完全相同:

this[someDynamicVariableWhichResolvesToAMethodName]();

2. Composition API 写法(<script setup>)

在 <script setup> 中没有 this,可以通过以下几种方式实现动态调用:

方式一:将方法统一挂载到一个对象中

<script setup>
const methods = {
  handleClick() {
    console.log('点击事件触发');
  },
  handleSubmit() {
    console.log('提交事件触发');
  }
};

// 假设动态变量的值是目标方法名
const targetMethod = 'handleClick';
// 执行动态调用
methods[targetMethod]();
</script>

方式二:用 reactive 包裹方法(适用于需要响应式的场景)

如果需要方法的引用具备响应式特性,可以用 reactive 包装:

<script setup>
import { reactive } from 'vue';

const dynamicMethods = reactive({
  sayHello() {
    console.log('Hello Vue 3');
  },
  sayHi() {
    console.log('Hi Vue 3');
  }
});

const targetMethod = 'sayHello';
dynamicMethods[targetMethod]();
</script>

方式三:单独定义方法后建立映射关系

如果方法是单独定义的,可手动创建映射对象来实现动态调用:

<script setup>
function foo() {
  console.log('foo 方法执行');
}

function bar() {
  console.log('bar 方法执行');
}

const methodMap = { foo, bar };
const currentMethod = 'bar';
methodMap[currentMethod]();
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:30:41