问题
I have a v-for loop that adds a section of divs to the page. On page load, the first one should be selected and then when you click another one, it should add the active class to the clicked div and remove the active class from the last div.
I tried the following which does not work. Any suggestions?
<div class="col-sm-6" v-for="(area, index) in areaSections">
<section class="monitoring-areas section" v-on:click="changeActive()">
<h3>
Area {{index + 1}}: {{area.title}}
<span class="section-image hidden-xs hidden-sm">
<i class="icon icon-zoom"></i>
<router-link to="/edit-monitoring-area">
<i class="icon icon-pen"></i>
</router-link>
</span>
</h3>
<div class="section-content" v-bind:class="{ active: area.isActive }">
<div class="row">
<div class="col-xs-5">
<div v-html="area.img"></div>
</div>
</div>
<div class="row hidden-lg visible-sm visible-xs visible-md">
<div class="col-lg-7 col-sm-8 col-xs-7 mb">
<p class="fw700"><span class="green">Email Alerts:</span> Monthly</p>
</div>
</div>
</div>
</section>
</div>
<script>
export default {
name: 'monitoringAreas',
data: function() {
return {
areaSections: [
{
title: 'Home',
address: {
street: '1517 Castillo St',
city: 'Santa Barbara',
state: 'CA',
postalCode: '93117'
},
img: '<img src="static/img/map-small-2.jpg" alt="map">',
alerts: 'Monthly',
isActive: true
},
{
title: "John's neighborhood",
address: {
street: '3142 West 4th St',
city: 'Santa Barbara',
state: 'CA',
postalCode: '93117'
},
img: '<img src="static/img/map-small-2.jpg" alt="map">',
alerts: 'Monthly',
isActive: false
},
{
title: "Near Work",
address: {
street: '174 Collegio Rd',
city: 'Santa Barbara',
state: 'CA',
postalCode: '93117'
},
img: '<img src="static/img/map-small-2.jpg" alt="map">',
alerts: 'Monthly',
isActive: false
},
]
}
},
methods: {
isActive() {
return this.isActive;
},
changeActive() {
this.isActive = !this.isActive;
}
}
}
</script>
回答1:
I suggest the following:
if you need only one section be active
at a time, create a data property isActive
and store current active index there. Also pass current index
to changeActive
method and store index or clear it if you click an active section again (to toggle class on second click):
new Vue({
el: '#app',
data: {
areaSections: [...],
isActive: null
},
methods: {
changeActive(index) {
this.isActive = this.isActive === index ? null : index
}
}
})
Then, in your template, make sure to pass index
into click listener:
<section class="monitoring-areas section" v-on:click="changeActive(index)">
In the end, bind active
class using new data prop:
v-bind:class="{ active: index == isActive }"
Full example can be found here: https://jsfiddle.net/wostex/63t082p2/73/
来源:https://stackoverflow.com/questions/44598187/vue-bind-click-that-adds-active-class-and-removes-from-the-last-one