Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 732
axlu Avatar asked Dec 27 '18 15:12

axlu


1 Answers

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-->
like image 120
Jeff Avatar answered Sep 22 '22 08:09

Jeff