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

In pursuit of increased speed

When using $routeProvider in Angular, I have noticed that every time I navigate to a specific route, I see the following logs in the console: XHR finished loading: "http://localhost:8080/root/partials/view1.html". XHR finished loading: "http://localhost:8 ...

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

Using React JS to automatically execute an event based on a specific state value

Is there a way to initiate an action from a main component when the child component's state reaches a specific value? Let's consider a scenario where I have a Parent component and a Child component, with the parent's state containing active ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Repairing div after upward scrolling and maintaining its fixation after refreshing the page

I have encountered two issues with this particular example: One problem is that the fixed_header_bottom should stay fixed beneath the fixed_header_top when scrolling up, causing the fixed_header_middle to gradually disappear as you scroll up, or vice v ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...

Occasionally, data may fail to be fetched when using a Jquery GET

Here's what I've narrowed it down to: $.getJSON('/drinks/getColors', function(items) { colors = items; }); $.each(colors, function(index2, value2) { if (value.name == value2.name) { curColor = value2.color; } }); ...

Is there a way to pull information from a string and organize it into a two-dimensional array?

Utilizing the axios library, I am pulling data from a website. Unfortunately, the data being fetched is in HTML format. The extracted data looks like this: 1 Agartala VEAT 120830Z 23004KT 5000 HZ SCT018 SCT025 34/27 Q1004 NOSIG= 2 Ahmedabad VAAH 120830Z 23 ...

What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code: $(&apos ...

Unable to successfully retrieve the output from a function within an AJAX request

Hey, I'm having trouble getting the value from this function. It keeps returning undefined and I can't figure out why. Here's the code snippet: function getData() { axios.get('/task') .then(response => { ...

Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them. Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle. The script looks like thi ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

Saving the current language (i18n) in local storage using VueJS

I'm working on a Vue app that utilizes Vue Routers and the Vue $i18n plugin. Here's how I've structured my HTML: <div class="locale-changer"> <select v-model="this.$i18n.locale" class="btn"> ...

Upon receiving data from the Api, the data cannot be assigned to the appropriate datatype within the Angular Object

I am encountering an issue with the normal input fields on my page: https://i.stack.imgur.com/qigTr.png Whenever I click on the "+" button, it triggers an action which in turn calls a service class with simple JSON data. My intention is to set selectionC ...

The Evolution of Alternatives to contentEditable

Related: ContentEditable Alternative I am curious about the timeline of online WYSIWYG editors prior to the existence of contentEditable. I remember using GDocs and GMail with rich-text features that functioned similarly to contentEditable. I would appre ...

Utilizing React Router: Combining MemoryRouter and Router for Dynamic Routing (leveraging memory for certain links while updating the URL for others)

While utilizing react-router-dom, I came across the helpful <MemoryRouter>. However, I am in need of having several routes that can read and write to/from the browser's URL. What is the best approach for implementing this functionality? Thank y ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

What is the best way to create a select box in React that allows for both single and multiple selections?

I recently started utilizing a new package for generating dynamic forms, which can be found at this link. Upon reading through the documentation, I attempted to create a select box as outlined in the instructions provided here. Despite following the step ...

Exploring JSON data structures using autocomplete functionalities

Here's the code I'm working with: <s:hidden id="s" value="%{Users}"/> The variable Users contains an array list of User objects. This code is written in Javascript. I want to access Users as JSON for auto-complete functionality: var valu ...