Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID.

However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers.

<template>
  <v-card elevation="2" class="experiences-container">
    <v-layout row wrap>
      <v-flex md3 sm12 xs12 class="relative">
        <div class="settings-list"
          :class="switchSetting ? 'open' : ''">
          <v-list>
            <v-list-tile
              v-for="(item, index) in menu"
              :key="index"
              :class="['experience-item', index === idSelectedSetting ? 'active' : '']"
              @click="updateSelectedSetting(index)"
            >
              <v-list-tile-content>
                <v-list-tile-title>{{ item.name }}</v-list-tile-title>
              </v-list-tile-content>
              <v-list-tile-action v-if="index == idSelectedSetting ? true : false">
                <v-icon>chevron_right</v-icon>
              </v-list-tile-action>
            </v-list-tile>
          </v-list>
        </div>

      </v-flex>
      <v-flex md9 sm12 xs12>
          <UserPasswordEdition class="setting-details"
            v-if="idSelectedSetting === 0"
            :class="switchSetting ? 'close' : ''"
          />
          <div
            class="setting-details"
            :class="switchSetting ? 'close' : ''"
            v-if="idSelectedSetting === 1">
            <div class="WIP">Another menu</div>
          </div>
      </v-flex>
    </v-layout>
  </v-card>
</template>

--

data() {
    return {
        menu: [
            { name: 'Password' },
            { name: 'Other menu' }
        ],
      idSelectedSetting: 0,
      switchSetting: false,
    };
  },
  methods: {
    updateSelectedSetting(id) {
      this.idSelectedSetting = id;
      this.closeSwitchSetting();
    },
    openSwitchSetting() {
      this.switchSetting = true;
    },
    closeSwitchSetting() {
      this.switchSetting = false;
    }
  }

--

I am trying to change the v-if statement here:

<UserPasswordEdition class="setting-details"
            v-if="idSelectedSetting === 0"
            :class="switchSetting ? 'close' : ''"
          />
          <div
            class="setting-details"
            :class="switchSetting ? 'close' : ''"
            v-if="idSelectedSetting === 1">
            <div class="WIP">Another menu</div>
          </div>

I attempted using a v-for loop, but I struggled with it as it displayed both contents on each menu. Any guidance on how to properly implement a v-for in this situation would be greatly appreciated. Thank you!

Answer №1

To start, you can establish an array containing all of your choices. Utilize :is for rendering individual components.

Make sure to include an index in your data and compare it with a selectedIndex during the rendering process.

data() {
 return {
  selectedIndex: 0, //default value goes here
  itemsToShow: [
   {
    id: 0,
    component: 'UserPasswordEdition',
   },
   {
    id: 1,
    component: 'OtherComponent'
   }
  ]
 }
}

Then update your template

<template>
  ...
  <v-flex md9 sm12 xs12>
    <component v-for="option in itemsToShow" 
               :key="option.id" 
               :is="option['component']
               v-if="selectedIndex === option.id"
    />
  </v-flex>
</template>

Note: This method is suitable when passing the same props to all components. Otherwise, the rendering logic may become more intricate.

Edit: In response to @Jer's caution regarding using v-for and v-if together.

You also have the option to employ a computed property to filter your array.

computed: {
 filteredItemsToShow() {
   return this.itemsToShow.filter(item => item.id === this.selectedIndex)
  }
}

Subsequently, utilize filteredItemsToShow during the rendering phase.

<template>
  ...
  <v-flex md9 sm12 xs12>
    <component v-for="option in filteredItemsToShow" 
               :key="option.id" 
               :is="option['component']
    />
  </v-flex>
</template>

Observe the elimination of v-if, as it is integrated into the computed property.

Answer №2

If you want to simplify your code, you can move your condition to a computed property like this:

<template>
  ...
  <v-flex md9 sm12 xs12>
    <UserPasswordEdition class="setting-details"
      v-if="!isSelectedSetting"
      :class="switchSetting ? 'close' : ''"
    />
    <div
      class="setting-details"
      :class="switchSetting ? 'close' : ''"
      v-if="isSelectedSetting"
    >
      <div class="WIP">Another menu</div>
    </div>
  </v-flex>
</template>

<script>
  export default {
    data() {
      return {
        menu: [
          { name: 'Password' },
          { name: 'Another menu' }
        ],
        idSelectedSetting: 0,
        switchSetting: false,
      };
    },
    computed: {
      isSelectedSetting() {
        return this.idSelectedSetting === 1
      }
    }
  }
</script>

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

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

Issue arises when child component fails to receive updated props from parent component after data changes in parent component

I am working with a template named Report.vue, which contains a data() property called dataSent:[]. Within this template, I have a component called BarChart that should receive an updated array from the dataSent property to display graphs. However, when I ...

Having trouble integrating a custom button into the toolbar of the Tinymce Vue.js wrapper

Struggling to add a custom button to the toolbar of tinymce using the vue.js wrapper (utilizing vue 3 and tinymce 5). The problem is that the custom button is not appearing in the toolbar. I have attempted the following steps, the logs in the init and set ...

Encountering a problem when trying to send an API request for multer in order to save

I encountered an issue with my node API that uses multer to store files. I am receiving an error when calling it and seeking assistance. Below is the code snippet along with the specific error message - Code - const storage = multer.diskStorage({ d ...

Enhance Your Vue Tables with Unique Custom Filters

I'm currently working on implementing https://github.com/matfish2/vue-tables-2 in Vue 2.1.8. Everything seems to be functioning flawlessly, but I need to incorporate custom filters to format certain fields based on their values. In my options object ...

Modify the page's query parameters by incorporating an input field within NextJS's App Router

I'm trying to update query parameters based on user input dynamically using the onChange event. However, I'm facing an issue where the query parameters are updated before the input value is updated after a slight delay. My aim is to achieve insta ...

Customizable form fields in AngularJS

Consider the scenario of the form below: First Name: string Last Name: string Married: checkbox % Display the following once the checkbox is selected % Partner First Name: Partner Last Name: [Submit] How can a form with optional fields be created in Angu ...

Synchronization between Vue and Node API on the go

Ensuring continuous synchronization with the backend API is crucial. What modifications made in the backend should automatically update the frontend in Vue? How can we achieve constant syncing with the API? Is setting intervals and calling the API the mo ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

What is the best way to retrieve the Axios response using Express?

I've recently delved into working with Express and I'm currently struggling with making an Axios request using route parameters, and then updating some local variables based on the response. Here's a snippet of what I've been working on ...

Exploring Vue.js: Navigating Through an Array of Images Nested Within Another Array

I am looking to showcase images stored in an array called "image" within another array named product. Essentially, if a product has an array of 3 images, I want to display all 3 images, and so on. Here is the code snippet: <template> <div c ...

Update the text on the button when tasks are in progress in React

I am working on a React project and I need to implement a button that changes its text from Save to Saving... when clicked, and then back to Save once the saving process is complete. My initial approach looks like this: import React from 'react&apos ...

Troubleshooting a Vue.js formatting problem in Visual Studio 2019

Encountering an issue with VS2019 while attempting to format this code section. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="milestone.ascx.cs" Inherits="uc.dms.milestone" %> <section class="content-header"> <h1> ...

Delivering Django and Vue applications efficiently through an Nginx server

I have a website that utilizes Django for the API and Vue for the frontend. When deploying the site, my current process involves: Generating a production build of the Vue app (npm run build) Transferring the Vue dist folder to a specific directory within ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

Updating dynamic content in IBM Worklight V6.1 with jQuery Mobile v1.4.3 requires waiting for the DOM to load

I need to dynamically update the content of a div within my HTML page structure. <!DOCTYPE HTML> <html> ... <body> <div data-role="page"> <div data-role="header"> //Image </div> <!-- Th ...

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Can you provide a list of factors that influence coverage? Additionally, is there a specific algorithm available for calculating

As part of my Angular project, I am currently focusing on writing unit test cases using the Jasmine Framework and Karma. To ensure thorough testing coverage, I am utilizing Coverage-html (Istanbul). When it comes to coverage, there are several important t ...