Toggle show/hide on specific element with Vue.js (cdn)

  • A+
Category:Languages

I'm using Vue.js (cdn) and axios to get stuff from heroku and mlab.

I want to display some information from the objects in a list and I want each line to act like a button or have some sort of onclick that displays more information from the same object below. like a drop down.

I tried the button v-on:click="visible = !visible"... And that works but it toggles show/hide on all of the elements, as expected.

I want to be able to toggle show/hide on a single element in a list of many.

This is what I have:

index.html

<div id="app">     <div class="list" v-for="drinks in rom">         <button v-on:click="visible = !visible">{{ drinks.brand }}</button>          <div class="hidden" v-show="!visible">             <p> {{ drinks.comment }} </p>         </div>      </div><!--list-->     </div><!--app--> 

main.js

new Vue({ el: '#app', data() {     return {         rom: null,         visible: true     } }, mounted() {     axios         .get('******')         .then(response => (this.rom  = response.data)) }}) 

What can I do?

 


You'll want to declare rom as an array:

data() {     return {         rom: []     } }, 

Then you can add a visible property to each data item in your API response:

mounted() {     axios         .get('******')         .then(response => (this.rom = response.data.map(drinks => {                 drinks.visible = true;                 return drinks;             })         )) }}) 

Then you can use that visible property in each loop of your v-for:

<div class="list" v-for="drinks in rom">     <button v-on:click="drinks.visible = !drinks.visible">{{ drinks.brand }}</button>      <div class="hidden" v-show="!drinks.visible">         <p> {{ drinks.comment }} </p>     </div>  </div><!--list--> 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: