应用程序在屏幕上有一些按钮,点击时应执行不同的功能。它有点像这样:
<template>
<ul>
<li v-for="MenuItem in MenuItems">
<button type="button" @click.prevent="handleClick({Function: MenuItem.Function.Name, Params: MenuItem.Function.Params })">
{{ MenuItem.Label }}
</button>
</li>
</ul>
</template>
<script setup>
const MenuItems = [
{
Label: `Edit`,
Function: {
Name: `editItem`,
Params: {
ItemID: 1
}
},
{
Label: `Delete`,
Function: {
Name: `deleteItem`,
Params: {
ItemID: 1
}
}
]
function handleClick({Function, Params}) {
Function.apply(Params) // throws not a function error
eval(Function+"()") // throws not a fuction error
}
function editItem(){
console.log(`edit item`);
}
function deleteItem(){
console.log(`about to delete item`);
}
</script>
我想要做的就是运行传递给Function
参数的所有内容handleClick()
,并将该参数作为需要执行Params
的参数包含进去,例如或;Function
editItem(1)
deleteItem(1)
尝试apply()
但eval()
似乎不起作用并抛出错误Uncaught TypeError: Function.apply is not a function
。我使用 VueJS 作为框架,但这实际上是一个 Javascript 问题。
将函数作为对象的方法并调用这些方法:
操场
我检查了你的代码。请尝试使用此代码库。
谢谢
Function
数组中的属性不是MenuItems
对实际函数的引用。它是一个字符串 (editItem
,deleteItem
),您不能像函数一样调用或应用字符串。要修复此问题,您可以传递实际的函数引用,而不是 MenuItems 数组中的字符串。以下是更正后的代码: