[Vuejs]-Toggle Class for an item Vue.js

2πŸ‘

βœ…

<div id="demo">

        <div class="input-group">
            <input class="form-control" v-model="searchText">
        </div>

        <script id="item-template" type="x-template">


            <div 
            class="stag"
            v-on="click: toggleHeight()"
            v-class="active: taller"
            >

                <h3>{{  item.question }}</h3>

                <h4>{{  item.answer }}</h4>

            </div>

        </script>

        <question 
            v-repeat="item: items | filterBy searchText" 
            v-transition="staggered" 
            stagger="200">
        </question>

    </div>
</div>

and the js:

Vue.component('question', {

        template: document.querySelector('#item-template'),

        data: function() {

            return {

                taller: false

            }

        },

        methods: {

            toggleHeight: function() {

                this.taller = ! this.taller

            }
        }

    });

    new Vue({

        el: '#demo',

        ready: function() {

            this.fetchItems();

        },

        methods: {

            fetchItems: function() {

                this.$http.get('/dev/frequently-asked-questions/api/index', function(items) {
                    this.$set('items', items);
                });

            }

        }

    });

Had to make use of components to target each item more directly.

πŸ‘€Stefkay

0πŸ‘

First of all, you only have one variable taller. Not one per faq. So you’d have to change it a bit to something like this:

new Vue({
    el: '#faq-list',
    data: {
        faqs: [{id:'foo',taller:false},{id:'bar',taller:true}]
    },
    methods: {
        toggleHeight: function (faq, ev) {
            faq.taller = false;
            ev.target.classList.add('active');
        }
    }
});

And your HTML to something like this:

<div id="faq-list">
<div class="panel panel-default"
  v-repeat="faq: faqs" 
  v-on="click: toggleHeight (faq, $event)"
  v-class="active: taller">
      {{ faq.id }}</div>
</div>

And for fun, I added CSS to see things working:

.active {
    color: red;
}

Here’s the JSfiddle, for your reference and to mess around with it. Click on one of the items in the list and it turns red.

πŸ‘€Nate Ritter

Leave a comment