我正在使用 BootstrapVue。对于我的问题:我有一个v-for
在我的模板中有两个buttons
.
循环我的v-for
my v-if
不生成唯一的IDs
单击一个按钮后,每个按钮都会被触发(from Open me!
to Close me!
以及其他方式).
我怎样才能让每个按钮只触发自己而不影响其他按钮?
我想我必须用我的n
of my v-for
但我实际上不知道如何将其绑定到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>
Edit:
您不需要每次创建行时都插入 id,而是可以使用 key 作为 id。请注意,inputs
是一个对象而不是数组,因此即使您想删除一行,也可以只传递索引并将其删除。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)