Vue.js 如何从多个元素中仅引用一个元素?vuejs
我正在学习vue,我遇到了这个问题。我有大约25个按钮,唯一改变的是标签和参考。每个都是这样的:Vue.js 如何从多个元素中仅引用一个元素?vuejs,vue.js,Vue.js,我正在学习vue,我遇到了这个问题。我有大约25个按钮,唯一改变的是标签和参考。每个都是这样的: <Button icon="pi pi-check" type="button" label="Min" class="p-button-text" ref="Min" @click="showActivatedButton"
<Button
icon="pi pi-check"
type="button"
label="Min"
class="p-button-text"
ref="Min"
@click="showActivatedButton"
v-bind:class="{ buttonActivated: buttonState }"
/>
<template>
<div>
<div
v-for="(button, index) in buttons"
:key="index"
>
<Button
icon="pi pi-check"
type="button"
:label="button.label"
class="p-button-text"
ref="button.ref"
@click="button.active = !button.active "
v-bind:class="{ buttonActivated: button.active }"
/>
</div>
</div>
</template>
<script>
export default {
data () {
return {
buttons: [
{ href: 'whatever', label: 'whatever', active: false },
{ href: 'whatever1', label: 'whatever1', active: false }
...add buttons
]
}
}
}
</script>
<style scoped>
.buttonActivated {
background: rgba(62, 70, 76, 0.16);
color: #3e464c;
border: 1px solid;
}
</style>
在方法中,我有以下内容:
buttonState: false;
showActivatedButton() {
this.buttonState = !this.buttonState;
}
.buttonActivated {
background: rgba(62, 70, 76, 0.16);
color: #3e464c;
border: 1px solid;
}
我的风格是:
buttonState: false;
showActivatedButton() {
this.buttonState = !this.buttonState;
}
.buttonActivated {
background: rgba(62, 70, 76, 0.16);
color: #3e464c;
border: 1px solid;
}
因此,我的想法是,一旦我单击其中一个按钮,这个类。buttonActivated将被添加到该按钮,如果我再次单击同一个按钮,该类将被删除。正如您现在看到的,无论我单击哪个按钮,它都会在每个按钮上添加和删除该类。请帮助:)每个按钮都需要一个单独的反应式
按钮state
属性。当前,您只有一个按钮state
,它在所有按钮之间共享。我建议创建一个子组件,您可以对每个按钮重复使用,并在子组件的data()
内声明buttonState
。您可以这样简化:
<Button
icon="pi pi-check"
type="button"
label="Min"
class="p-button-text"
ref="Min"
@click="showActivatedButton"
v-bind:class="{ buttonActivated: buttonState }"
/>
<template>
<div>
<div
v-for="(button, index) in buttons"
:key="index"
>
<Button
icon="pi pi-check"
type="button"
:label="button.label"
class="p-button-text"
ref="button.ref"
@click="button.active = !button.active "
v-bind:class="{ buttonActivated: button.active }"
/>
</div>
</div>
</template>
<script>
export default {
data () {
return {
buttons: [
{ href: 'whatever', label: 'whatever', active: false },
{ href: 'whatever1', label: 'whatever1', active: false }
...add buttons
]
}
}
}
</script>
<style scoped>
.buttonActivated {
background: rgba(62, 70, 76, 0.16);
color: #3e464c;
border: 1px solid;
}
</style>
导出默认值{
数据(){
返回{
按钮:[
{href:'where',标签:'where',活动:false},
{href:'whatever1',标签:'whatever1',活动:false}
…添加按钮
]
}
}
}
.按钮有动力{
背景:rgba(62,70,76,0.16);
颜色:#3e464c;
边框:1px实心;
}