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

It appears that the home page of next.js is not appearing properly in the Storybook

Currently, I am in the process of setting up my next home page in storybooks for the first time. Following a tutorial, I successfully created my next-app and initialized storybooks. Now, I am stuck at importing my homepage into storybooks. To achieve this, ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

Set the style to be displayed as a block element

I am working on a Rails application that contains some <li> elements with the CSS property display: none;. I want these elements to only appear on the page when they are being dragged. However, there are some elements that do not have the display: no ...

Manipulate the timing of css animations using javascript

I am currently working with a progress bar that I need to manipulate using JavaScript. The demo of the progress bar has a smooth animation, but when I try to adjust its width using jQuery $($0).css({'width': '80%'}), the animation disap ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...

Tips for updating server-side variables from the client-side in Next.js

There is a code snippet in api/scraper.js file that I need help with. const request = require("request-promise"); const cheerio = require("cheerio"); let url = "https://crese.org/distintivo-azul/"; let result; request(url, ...

Embedding JSON data in a GSP page

My goal is to transfer JSON data to a GSP page and present it in a table format. The expected JSON structure: { "data": [ [ "Tiger Nixon", "System Architect", "Edinburgh" ] ]} I attempted to achieve this with the following co ...

Exploring alternative applications of defineModel in Vue 3.4 beyond just handling inputs

The examples provided for defineModel in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to ...

Leveraging Environment Variables in Separate JavaScript Files within a Node Express Application

After trying various methods and searching extensively online, I am struggling to use environment variables in a separate JavaScript file within an Express App. My Setup: In my Express app, I have an index.js file that serves an HTML page with associated ...

typescript unconventional syntax for object types

As I was going through the TypeScript handbook, I stumbled upon this example: interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; ...

Having trouble retrieving data from the server for the POST request

I am fairly new to using Jquery and Ajax requests. I'm currently working on a website where I have a simple form that collects an email address from users and sends it to the server. However, I'm struggling to figure out how to capture the form d ...

various stunning galleries accessible from a single page of thumbnail images

I'm trying to create a unique gallery experience on my website. I have a set of 6 images, each featuring a different house. What I want is for each image, when clicked, to open up a fancybox gallery showcasing 4 more detailed photos of the same house. ...

Integrate a Facebook Like-box within a customized jQuery modal window

I've been working on inserting the Facebook like-box code into my page and trying to display it within a jQuery modal dialog. Here's the code I'm using: <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>< ...

I utilized the `<script src="sample.pdf"></script>` tag in my HTML code and surprisingly, the JavaScript within the PDF document was still able to execute

Recently, I encountered a situation where I included a PDF file with JavaScript code in the src attribute of a script tag in my code. Surprisingly, the JavaScript code executed without any issues. This made me wonder if I can use any type of file extension ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

Algorithm for encryption and decryption using symmetric keys

Can anyone recommend a reliable symmetric-key encryption algorithm that works seamlessly with both JavaScript and Java programming languages? I attempted to implement one myself, but encountered some complications related to encoding. ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...

Triggered by each user interaction, the callback function is activated

I need to add a timeout feature to my AngularJS web application. Each time a user interacts with the site, a timer is set for 10 minutes. Once this timer runs out on the client-side, a request is sent to the server signaling a timeout. What is the best wa ...