问题描述
我有一些可重用的组件,每当添加一个组件时,它就会被推送到数组等中。问题是:如何确保这些可重用组件中的方法仅针对相应的组件而不对所有组件都运行。
示例:使用@click事件打开模态,模态显示了我添加组件的确切次数(预期,但是我想更改此值,因此它仅对相应组件显示一次)
添加组件:
<template v-for="(comp,index) in comps">
<component
:is="comp"
:key="index"
:currentIndex="currentIndex"
v-on:delete="deleteComp($event)"
></component>
</template>
某些组件内的方法相同:
methods: {
showModal() {
this.$bvModal.show('modalSmall');
}
}
解决方法
执行此操作的最佳方法是传递id作为不同组件的道具。
<template v-for="(comp,index) in comps">
<component
....
:id="comps.id" // you could create a computed property to generate an id based on a number or some other unique identifier
....
></component>
</template>
然后在您的组件中
Component.vue
props: {
id: {
type: string,required: true
}
}
methods: {
showModal() {
this.$bvModal.show(id);
}
}
请记住,将模板中每个模式的ID从modalSmall
更改为id
(ID属性)。