Wes
Wes

Reputation: 39

Nuxt.js: Iterating in method causes problems

After a click event fires, I try to iterate over the length of a specific array. Each item in the array is linked to a HTML element with a v-if statement. The elements are shown when the corresponding item in the array is set to true.

After clicking, the elements however are not showing up, and upon closer inspection, the array looks like this:

visibleQuestions: [ null, null, null, true ]

In this case there were 3 questions that needed to show up.

How can I fix this? The relevant piece of code is this:

<template>
    <fieldset v-for="(item, questionIndex) in questions" v-if="visibleQuestions[questionIndex]">
        ....
    </fieldset>
    <button @click="showAll(questions.length)">Show all</button>
</template>

<script>
    export default {
        asyncData(context) {
            return context.app.$storyapi.get('cdn/stories', {
                version: 'draft',
                startsWith: '/subjects/biology/hl/1999-may'
            }).then(response => {
                console.log(response.data.stories[0].content.question);
                return {
                    questions: response.data.stories[0].content.question
                }
            });
        },
        data() {
            return {
                visibleQuestions: []
            }
        },
        methods: {
            showAll: function(questionAmount) {
                for (let i = 0; i < questionAmount; i++) {
                    this.$set(this.visibleQuestions, questionAmount, true);
                }
            }
        }
    }
</script>

Upvotes: 0

Views: 702

Answers (1)

Max Sinev
Max Sinev

Reputation: 6019

Change questionAmount to i in Vue.set call in showAll method:

       showAll: function(questionAmount) {
            for (let i = 0; i < questionAmount; i++) {
                this.$set(this.visibleQuestions, i, true);
            }
        }

Upvotes: 2

Related Questions