如何在每个对象上获得不同的onclick事件,当循环通过对象数组VUE3



我有一个使用v-for和props循环遍历的组件。我希望每个渲染组件有一个不同的点击事件,但我不知道如何传递一个函数作为一个道具。

代码:

组件:

<template>
<div v-on:click="cardProperties.scrollFunction" :id="cardProperties.id" class="flex text-text-color justify-around text-center bg-container-color h-1/6 w-2/12 rounded-3xl shadow-lg m-4 cursor-pointer ease-in-out duration-500 hover:bg-container-hover-color opacity-95">
<div class="py-6">
<h2>{{cardProperties.title}}</h2>
<font-awesome-icon class="h-12 my-4" :icon="cardProperties.icon" />
<p>{{cardProperties.text}}</p>
</div>
</div>
</template>

<script>


export default {
name: 'card-container',
components: {
},
props: {
cardProperties: Object,
},
data() {
return{
cardProps: this.cardProperties
}
},
methods: {
musicScroll() {
const musicDiv = document.getElementById("music");
if(musicDiv != null){
musicDiv.scrollIntoView({behavior: 'smooth'})
}
},
maoScroll() {
const maoDiv = document.getElementById("mao");
if(maoDiv != null){
maoDiv.scrollIntoView({behavior: 'smooth'})
}
},
},
}
</script>

App.vue:

<card 
v-for="cardProperties in cardPropsArray"
v-bind:key="cardProperties.text"
:cardProperties = cardProperties
/>

cardPropsArray:[
{
id: "music",
scrollFunction: "musicScroll()",
title: "Musik",
icon: "fa-solid fa-music",
text: "/play"
},
{
id: "mao",
scrollFunction: "maoScroll()",
title: "Med Andra Ord",
icon: "fa-solid fa-hourglass-end",
text: "/MAO"
},

我试图传递"scrollFunction"作为一个道具,但因为它以字符串的形式发送道具,所以它不起作用。它会导致错误消息:"TypeError: $props.cardProperties。scrollFunction不是一个函数">

card-container组件内部发出一个函数名作为参数的事件:

<div v-on:click="$emit('call-method',cardProperties.scrollFunction)" :id="cardProperties.id" class="flex ...">
<div class="py-6">
<h2>{{cardProperties.title}}</h2>
<font-awesome-icon class="h-12 my-4" :icon="cardProperties.icon" />
<p>{{cardProperties.text}}</p>
</div>
</div>

在parent中定义发出的事件处理程序,并使用[]访问器调用方法,如this[funcName]():

<card 
v-for="cardProperties in cardPropsArray"
v-bind:key="cardProperties.text"
:cardProperties = cardProperties
@call-method="run"
/>
...
<script>
cardPropsArray:[
{
id: "music",
scrollFunction: "musicScroll",
title: "Musik",
icon: "fa-solid fa-music",
text: "/play"
},
{
id: "mao",
scrollFunction: "maoScroll",
title: "Med Andra Ord",
icon: "fa-solid fa-hourglass-end",
text: "/MAO"
},
... 
methods:{
run(funcName){
this[funcName]();
},
....
}
</script>

可以通过省略引号使函数成为对象属性!带引号的总是字符串:

{
id: "music",
scrollFunction: musicScroll,
title: "Musik",
icon: "fa-solid fa-music",
text: "/play"
}

最新更新