Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed.

Although the function is operational, there is a slight issue where clicking on any icon reveals all answers simultaneously. My goal is to refine this functionality so that only the corresponding answer appears upon clicking.

I would greatly appreciate any assistance or suggestions you may have regarding this matter.

HTML


    <div class="faq-question">
      <p class="question">Question 1. This is question One</p>
      <font-awesome-icon @click="toggleAnswer()" :icon="['fas', 'angle-right']" class="arrow-icon" />
    </div>
    <div class="faq-answer">
      <p class="answer" v-show="togglerAnswer">{{casino[0].FAQ_Answer_One}}</p>
    </div>
    <div class="faq-question">
      <p class="question">Question 2. This is question Two</p>
      <font-awesome-icon @click="toggleAnswer()" :icon="['fas', 'angle-right']" class="arrow-icon" />
    </div>
    <div class="faq-answer">
      <p class="answer" v-show="togglerAnswer">{{casino[0].FAQ_Answer_Two}}</p>
    </div>

JS:

toggleAnswer() {
            if(!this.togglerAnswer) {
                this.togglerAnswer = true;
            } else {
                this.togglerAnswer = false;
            }
        }

@EDIT

export default {
    asyncData({ params }) {
        return axios.get(casinoURL + params.casinos).then(res => {
            return { 
                casino: res.data, 
                casinoID: res.data[0].id, 
                casinoBonus: res.data[0].bonuses,
                casinoPros: res.data[0].brand_pros,
                casinoCons: res.data[0].brand_cons,
                casinoGames: res.data[0].verticals,
                casinoTags: res.data[0].brand_tags,
                casinoAnswers: res.data[0].FAQ_Answer_One,
            };
        })
    },
    data() {
        return {
            casino: [],
            casinoID: null,
            casinoPros: [],
            casinoCons: [],
            casinoGames: [],
            casinoTags: [],
            casinoAnswers: [],
            togglerAnswer: false,
        }
    },
    methods: {
        toggleAnswer() {
            if(!this.togglerAnswer) {
                this.togglerAnswer = true;
            } else {
                this.togglerAnswer = false;
            }
        }
    }
}

Answer №1

introduce a new attribute named toggledAnswerIndex which is initially configured to -1 and apply it like this:

@click="toggleAnswer(1)" // 1 for answer one, 2 for answer two, and so forth

within the function :

toggleAnswer(index) {
            if(!this.togglerAnswer) {
                this.togglerAnswer = true;
              this.toggledAnswerIndex =index
            } else {
                this.togglerAnswer = false;
                this.toggledAnswerIndex =-1;
            }
        }

inside the template :

 <div class="faq-answer">
      <p class="answer" v-show="togglerAnswer && toggledAnswerIndex ===1 ">{{casino[0].FAQ_Answer_Two}}</p>
    </div>

Update

you need to return an array called casinoAnswers in asyncData as follows:

 async asyncData({ params }) {
    let res= await axios.get(casinoURL + params.casinos)
     return {casinoAnswers :res.data}
 
 }

and eliminate casinoAnswers from data option.

template :

 <template v-for="(cas,index) in casinoAnswers ">
 <div class="faq-question" v-for="(cas,index) in casino">
  <p class="question">Question {{index}}. This is question {{index}}</p>
  <font-awesome-icon @click="toggleAnswer(index)" :icon="['fas', 'angle-right']" class="arrow-icon" />
</div>
 <div class="faq-answer">
   <p class="answer" v-show="togglerAnswer && toggledAnswerIndex===index">{{cas.FAQ_Answer_One}}</p>
</div>
</template>

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

How can GraphQL facilitate JOIN requests instead of multiple sequential requests?

I am working with two GraphQL types: type Author { id: String! name: String! } type Book { id: String! author: Author! name: String! } In my database structure, I have set up a foreign key relationship within the books table: table authors (e ...

Dimensions of Collada Element

This is my first time delving into the world of javascript, WebGL, and Three.js. I successfully added a dae 3D model to my scene, but now I need to determine its size in order to generate objects within it. However, upon adding the dae object, it appeared ...

Guide to building a multi-dimensional array from a flat object

My endpoint is outputting data in a specific format: const result = [ {id: 4, parentId: null, name: 'Fruits & Veggies'}, {id: 12, parentId: 133, name: 'Sanguinello'}, {id: 3, parentId: 4, name: 'Fruits'}, {id: 67, ...

Submitting form data to PHP without refreshing the page

I've been attempting to send form data, specifically an array, to a PHP file without having the page refresh. I've implemented AJAX for this purpose but it doesn't appear to be working as intended. Below you'll find the syntax of the fo ...

"Revamping the text style of input materials in React JS: A step-by

How can I modify the style of the text field component in Material UI? Specifically, I would like to change the appearance of the text that the user enters. I have attempted to use the Material API, but it has not provided the desired results. Here is an ...

Encountering an issue while attempting to utilize the .find() method in Mongoose

Currently, I am in the process of setting up a database using MongoDB and integrating the Mongoose ODM with Node.js. After running the code multiple times without any issues, I encountered an unexpected error when adding the last block to utilize the .find ...

Successfully changing the source and tracking of a video through an onclick button, but the video content remains unchanged

I apologize if this post is a duplicate, but I couldn't find the answer in previous threads. I'm attempting to change the video source using an onclick button. However, even after changing the source, the video remains the same. <video width ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

Generate text input fields dynamically and store their values in an array using the Backbone.js framework

Is there a way to dynamically create text boxes based on a number input field with type='number'? Essentially, every time a user increments the number input, a new text box should be added to the backbone.js view. Additionally, when values are en ...

Guide on enabling automatic rotation using Javascript

Recently, I came across a slider online that unfortunately did not have an autorotate feature. Despite my attempts to add an autorotate function using setTimeout and click functions, I was unsuccessful. This particular slider contains 4 buttons for each s ...

Using PHP and MySQL to create checkboxes populated with data retrieved from a database, and then submitting two parameters

Hey there, I've been struggling with this issue for quite some time. I'm trying to create a list with checkboxes populated from a database that includes [checkbox of car id and value][brand][model]. The goal is to select two cars from the list, ...

Using jQuery to dynamically render unordered lists from JSON data

Struggling to create a dynamic unordered list with multiple nested levels? Finding it difficult to render the necessary markup for future functionality? Take a look at the HTML structure I've created on this jsfiddle link: <ul class="nav nav-sideb ...

Using a directive to implement Angular Drag and Drop functionality between two tables with 1000 records

My code is functional, but there seems to be a delay in the appearance of the helper(clone) when dragging starts. I have two tables - one for the include list and another for the exclude list. Users can drag table rows from the include table to the exclud ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Avoid removing content when using bootstrap popover

My goal is to incorporate HTML within a Bootstrap 5 popover. I made some modifications to the code to extract HTML content from a specific div without using the data-bs-content attribute. The current code structure is as follows: $(document).ready(fu ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

Tips for calculating the total of each row and column in a table with jQuery

<table id="repair-invoice"> <tr> <th>Item</th> <th>Parts</th> <th>Labor</th> <th>Total</th> </tr> <tr> <td>Oil Change</td&g ...

Wait for all asynchronous functions in Node.js to finish before proceeding with the remaining code

I am facing an issue in my code where I have 2 for loops executing the same async function, but I need the code to wait until both loops finish executing before proceeding. Here is a snippet of my code: for(var a = 0; a < videoIds.length; a++){ ...

What causes the scope to shift when incorporating a Lazy function within the module pattern in JavaScript?

Implementation 1: Working code in normal var foo1 = function() { var t1 = new Date(); console.log("initialize - one time only " + this); foo1 = function() { console.log("Executes every time after initializing (initialize should not e ...

Privacy protection feature in Firefox is preventing data from being pushed to Google Tag Manager's Datalayer

Recently, I discovered that the conversion tracking in Google Analytics for a website we developed and maintain has been inaccurate by 20% - 40% daily. After testing in various browsers except Firefox, conversions are reflected in Analytics immediately wi ...