gpt4 book ai didi

javascript - 是否可以在 V-for 中附加多个函数?

转载 作者:行者123 更新时间:2023-12-05 01:55:13 26 4
gpt4 key购买 nike

我有一个元素数组,我需要将这些元素渲染到一个 div 中并为每个元素附加不同的点击功能。

<template>
<div class="container">

<div v-for="option in options" :key="option.id" @click="option.clickFunction">.
{{option}}
</div>

</div>
</template>

<script>
export default{
data(){
return{
options: [
{
id: 1,
text: "option 1",
clickFunction: "function1",
},
{
id: 2,
text: "option 2",
clickFunction: "function2",
},
{
id: 3,
text: "option 3",
clickFunction: "function3",
},
{
id: 4,
text: "option 4",
clickFunction: "function4",
},
{
id: 5,
text: "option 5",
clickFunction: "function5",
},
],
}
}
methods:{
//defining all click functions
}
}
</script>

上面的方法我都试过了,还是不行,请问有什么办法吗?

最佳答案

这对您不起作用,因为每个对象中的每个 clickFunction 属性都是一个字符串。 @click 属性应该如何处理常规旧字符串?尝试

<template>
<div class="container">

<div v-for="option in options" :key="option.id" @click="option.clickFunction">
<!-- I'm guessing you meant option.text here -->
{{option.text}}
</div>

</div>
</template>

<script>
export default{
data(){
return{
// pass functions around instead of strings!
options: [
{
id: 1,
text: "option 1",
clickFunction: this.myUniqueClickHandler,
},
{
id: 2,
text: "option 2",
clickFunction: this.myOtherUniqueClickHandler,
},
// etc.
],
}
}
methods:{
myUniqueClickHandler() {
// ...
},
myOtherUniqueClickHandler() {
// ...
}
}
}
</script>

关于javascript - 是否可以在 V-for 中附加多个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70321258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com