Nuxt.js: Issues arise when iterating within a method

Following a click event trigger, I attempt to iterate through a specific array's length. Each element in the array is associated with an HTML element using a v-if statement. These elements should appear when the corresponding array item is set to true.

However, after clicking, the elements are not appearing, and upon further investigation, the array seems to be like this:

visibleQuestions: [ null, null, null, true ]

In this scenario, there were 3 questions that were supposed to be displayed.

What steps can be taken to rectify this issue? The critical code snippet is as follows:

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

Answer №1

Modify the variable questionNumber to i when using the Vue.set method within the showAllQuestions function:

       showAllQuestions: function(questionNumber) {
            for (let i = 0; i < questionNumber; i++) {
                this.$set(this.displayedQuestions, i, true);
            }
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting up automatic tooltip validation messages?

After creating a sample file for validation, everything seems to be working smoothly... However, I now have a specific requirement - I would like to make some modifications while validating. The error message should automatically display in a tooltip. Thi ...

Encountering an issue when managing input using React hooks

I am using hooks to manage the user's text input in my code. const [inputValues, setInputValues] = useState({ firstName:"", lastName:"", email:"", telNum:"", contactType:"Tel.", message:"", ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Using a variable value as a regular expression pattern: A beginner's guide

I'm at my wit's end - I can't figure out where I'm going wrong. I've been attempting to replace all instances of '8969' but I keep getting the original string (regardless of whether tmp is a string or an integer). Perhaps ...

Submitting an Ajax request with a GET method instead of the expected POST

I am trying to set up a form on my website: <form onsubmit="return sendEmail()" id="emailForm" name="emailForm"> <input type="hidden" name="_cc" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Error Encountered: Unexpected Identifier in Angular 7 External jQuery Plugin

Struggling to convert a jQuery template to Angular7, I'm facing an issue with loading .js files from the assets folder in the original template to make it functional. Upon starting the application with: ng serve, I encounter the following error in th ...

Timing the loop iteration before passing the value to the function included

I'm currently exploring how to implement a timeout for a function within a loop iteration in an Ionic application using TypeScript. setInterval will execute the function at equal time intervals in a continuous loop: setInterval(() => { th ...

Adding a property with the identical name in VueJS: A step-by-step guide

Currently, I am utilizing a Vue2 component framework called vuetify, and I have encountered an issue with the input textbox's class. Within the textbox component, the code appears as follows: <template lang="pug"> div( class="input-group ...

Implementing Routing in a Vue.js cli 3.0 project

I am intrigued by the new Vue.js 3.0 plugin architecture, however, I have noticed that it lacks a router plugin. It is interesting that even if I decide not to include routing when initially creating a project using vue create my-project, there doesn' ...

Display a specific section of an image as the background in a div, with the image scaled and positioned perfectly

Utilizing a 1900 x 1080 image within a div as the background <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <style> html,body { height:100%; } #imageHolder{ ...

Leveraging the power of CreateJS in partnership with Chart.js

Can anyone provide guidance on how to integrate a chartjs radar chart into a createjs canvas stage? I am attempting to use chartjs to generate the chart and then position it within the createjs stage. Any suggestions or advice would be greatly appreciate ...

Pseudo code example for fetching data from MySQL using PHP associative arrays

I am faced with the task of retrieving data from two MySQL tables - products and prodGroups. The desired outcome is to have this information structured in the form of an associative array like so: Array ( [0] => Product Group 1 =& ...

Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving ...

A guide on breaking down a URL string containing parameters into an array with the help of JavaScript

I need help splitting a long string into an array with specific index structure like this: fname=bill&mname=&lname=jones&addr1=This%20House&... I am looking to have the array set up as shown below: myarray[0][0] = fname myarray[0][1] = b ...

When attempting to display database information, the word 'array' is unexpectedly printed instead

Every time I run my code, it displays the word "array" instead of the actual database information. Even when using print_r() or var_dump(), it still just dumps all the array details. When I use var_dump: array(1) { ["Team"]=> string(8) "Oakville" } ar ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

The jQuery show/hide functionality is malfunctioning

In my PHP code, I have the following loop: foreach ($sid as $key => $value) { $sql = " a sql query "; $vehicle->rowQuery($sql); $numRows = $vehicle->rows; while ( $data = $vehicle->result->fetch_assoc()) { $ ...

What causes the discrepancy between the nodejs package on GitHub and the version downloaded through npm?

After committing to installing a nodejs package with npm install -g package_name, I noticed that some of the downloaded packages have different files compared to the same package on Github. Why is this discrepancy present? ...

What is the best way to set one property to be the same as another in Angular?

In my project, I have defined a class called MyClass which I later utilize in an Angular component. export class MyClass { prop: string; constructor(val){ this.prop = val; } public getLength(str: string): number { return str.length; } ...