问题
I have created buttons dynamically with v-for and now I want that the button which is clicked changes the colour and the other have all the same colour.
<template>
<div id="exam-screen" class="exam jumbotron">
<h1>{{ title }}</h1>
<div class="row">
<p class="col-md-6" v-bind:key="exam.id" v-for="exam in getExam">
<button
class="exam exam-btn btn btn-secondary btn-lg btn-block"
v-bind:id="
'exam-' + exam.id + '-' + exam.season + '-' + exam.year + '-btn'
"
>
<span>{{ exam['season_de'] }} {{ exam.year }} </span>
</button>
</p>
</div>
<div class="row">
<p class="col-md-8"></p>
<BaseButton>{{ startButton }}</BaseButton>
</div>
</div>
</template>
I know that I need a v-on:click directive, but I don't know how I change the color...
I already managed that in JavaScript, but I don't know how it works in Vue.js...
How I do it in JavaScript:
function selectAnswer(id) {
$(id).addClass("btn-primary");
$(id).removeClass("btn-secondary");
}
function deselectAnswer(id) {
$(id).addClass("btn-secondary");
$(id).removeClass("btn-primary");
}
I hope someone can help me...
回答1:
You can add & remove a class from the buttons using @click & :class like this:
new Vue({
el: "#myApp",
data: {
items: [{text: 'This is Button 1'},{text: 'This is Button 1'},{text: 'This is Button 3'}]
},
methods: {
toggleClass(index) {
this.items.forEach(item => item.active=false);
let item = this.items[index];
item.active = !item.active;
this.$set(this.items, index, item);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="myApp">
<div v-for="(item, index) in items" :key="index">
<button
:class="{ 'btn-primary': item.active, 'btn-secondary': !item.active}"
@click="toggleClass(index)"
class="btn btn-md btn-block m-3">
<span>{{ item.text }} </span>
</button>
</div>
</div>
Please note that @click
is just a shorthand for v-on:click
and :class
is just a shorthand for v-bind:class
. Also, we need to remove btn-secondary
class that we set initially to the buttons otherwise btn-primary
does not take effect on the button on click.
来源:https://stackoverflow.com/questions/60933983/vue-js-i-have-dynamic-buttons-and-i-want-that-the-color-changes-if-i-clicked-o