我正在使用 BootstrapVue。对于我的问题:我有一个 v-for
在我有两个 buttons
的模板中.
循环我的v-for
我的 v-if
不会生成唯一的 IDs
然后单击一个按钮后,每个按钮都会被触发(从 Open me!
到 Close me!
以及其他方式)。
我怎样才能设法让每个按钮只触发自己而不影响另一个?
我想我必须使用我的 n
我的v-for
但我实际上不知道如何将它绑定(bind)到 v-if
..
提前致谢!
<template>
<div>
<div v-for="n in inputs" :key="n.id">
<b-button v-if="hide" @click="open()">Open me!</b-button>
<b-button v-if="!hide" @click="close()">Close me! </b-button>
</div>
<div>
<b-button @click="addInput">Add Input</b-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
id: null,
inputs: [{
id: 0
}],
hide: true,
};
},
methods: {
open() {
this.hide = false
},
close() {
this.hide = true
},
addInput() {
this.inputs.push({
id: this.id += 1;
})
}
}
};
</script>
最佳答案
一切似乎都很好。为了处理每个按钮触发器,
你可以像这样维护一个对象:
<script>
export default {
data() {
return {
inputs: [{id: 0, visible: false}],
};
},
methods: {
open(index) {
this.inputs[index].visible = false
},
close(index) {
this.inputs[index].visible = true
},
addInput() {
this.inputs.push({id: this.inputs.length, visible: false});
}
}
};
</script>
你的模板应该像<template>
<div>
<div v-for="(val, index) in inputs" :key="val.id">
<b-button v-if="val.visible" @click="open(index)">Open me!</b-button>
<b-button v-if="!val.visible" @click="close(index)">Close me! </b-button>
</div>
</div>
</template>
编辑:您不需要每次创建行时都插入 id,而是可以使用键作为 id。请注意
inputs
是一个对象而不是数组,因此即使您想删除一行,您也可以传递索引并将其删除。
关于javascript - 如何将 v-for 的值绑定(bind)到 v-if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69807074/