Phreak
Phreak

Reputation: 301

Vue component toggle

I'm fairly new to Vue, working on a FAQ list component which toggles the answer on click of a question. I'm not sure how to toggle a class with a Vue Component/with a template.

Also, is having the show attribute inside the data(faq_list) a good way to do this?

Code below.

<div id="app">
    <faqs :list="faq_list" :active.sync="active"></faqs>
    <pre> {{$data| json}} </pre>
</div>

<template id="faq-template">
    <ol>
        <li v-for="list_item in list">
            <div class="question"> {{list_item.question}} </div>
            <div  v-if="toggleActive" @click='toggleActive(list_item)'>
                {{list_item.answer}}
            </div>
            <strong @click="removeFaq(list_item.answer)">x</strong>
        </li>
    </ol>
</template>

Vue.component('faqs', {
        props: ['list', 'active'],

        template: '#faq-template',

        methods: {
            removeFaq: function(list_item){
                this.list.$remove(list_item);
            },

            toggleActive: function(list_item) {
                console.log(list_item.show);
              list_item.show = !list_item.show;
            }

        }
    });

    new Vue({
        el: '#app',

        data: {

            active: {},

            'faq_list' : [
                { question: 'q01', answer: 'q1',  show: false},
                { question: 'q02', answer: 'a2',  show: false},
                { question: 'q03', answer: 'a3',  show: false},
                { question: 'q04', answer: 'a4',  show: false},
                { question: 'q05', answer: 'a5',  show: false}
            ]
        }
    });

Upvotes: 0

Views: 2437

Answers (1)

Jeff
Jeff

Reputation: 25221

<li v-for="list_item in list">
    <div class="question" @click='list_item.show = !list_item.show'> {{list_item.question}} </div>
    <div v-if="list_item.show">
        {{list_item.answer}}
    </div>
    <strong @click="removeFaq(list_item)">x</strong>
</li>
  1. You had v-if="toggleActive" but it should be v-if="list_item.show"

  2. I moved the click up to the question div so you could show/hide the div, otherwise once it was hidden you couldn't click it

  3. simplified @click='list_item.show = !list_item.show' although yours works also :)

  4. Had the wrong argument sent to the remove function (you sent list_item.answer when you wanted list_item

Upvotes: 3

Related Questions