axlu
axlu

Reputation: 113

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?

Upvotes: 10

Views: 13523

Answers (3)

lovis91
lovis91

Reputation: 2171

You can add a visible property to your drink object, and then

v-on:click="drink.visible = !drink.visible"

Or you can create an array mapped with your drink with the id as key, and true or false as value and then :

v-on:click="drinksVisibility[drink.id].visible = !drinksVisibility[drink.id].visible"

Upvotes: 3

Sandeep Soni
Sandeep Soni

Reputation: 85

you can have a visible property in each object and render elements

rom : [{brand: 'drink1',visible: false,comment: 'drink1 - comment'},
  {brand: 'drink2',visible: false,comment: 'drink2 - comment'}]

then write a toggle function to show/hide an element by passing an index value to modify particular object visible value true/false

<button v-on:click=toggle(index)>{{ drinks.brand }}</button>

example : https://codepen.io/sandeep821/pen/YdxjWg

Upvotes: 1

Jeff
Jeff

Reputation: 25221

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-->

Upvotes: 9

Related Questions