How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once.

In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type.

The goal is to deactivate all Breakfast options if the user selects any Dinner recipes, and vice versa.

For those interested in tackling this challenge, here is my codepen link: https://codepen.io/5less/pen/eYmaazj

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      selected: [],
      recipes: [
        {
          'id': 1,
          'name': 'Pizza',
          'type': 'Dinner',
          'disabled': false
        },
        {
          'id': 2,
          'name': 'Omelet',
          'type': 'Breakfast',
          'disabled': false
        },
        {
          'id': 3,
          'name': 'Scrambled Eggs',
          'type': 'Breakfast',
          'disabled': false
        },
      ],
    }
  }
})
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-row align="center">
        <v-col cols="12" sm="4">
          <v-subheader v-text="'You can only select one type'"></v-subheader>
        </v-col>
        <v-col cols="12" sm="2">
          <v-select
            v-model="selected"
            :items="recipes"
            label="Select"
            multiple
            hint="Choose your meal"
            persistent-hint
            item-value="id"
            item-text="name"
          ></v-select>
        </v-col>
      </v-row>
      Selected: {{ selected }}<br>
      Recipes: {{ recipes }}
    </v-container>
  </v-app>
</div>

Answer №1

Customize item disabling in Vuetify

Utilizing the item-disabled prop of Vuetify's v-select, you can define a function to determine if an item should be disabled or not.

<template>
   <v-select
     v-model="selected"
     :item-disabled="disableItem"
     :items="items"
     multiple
   />
</template>
<script>
export default {
  data () {
    return {
      selected: ['name'],
      items: [
        {
          text: 'Name A to Z',
          value: 'name'
        },
        {
          text: 'Name Z to A',
          value: '-name'
        },
        {
          text: 'Most recent to oldest',
          value: '-updated_at'
        },
        {
          text: 'Oldest to most recent',
          value: 'updated_at'
        }
      ]
    }
  },
  methods: {
    disableItem (item) {
      let invertedValue

      if (item.value.match(/^-/)) {
        invertedValue = item.value.replace(/^(-)/, '')
      } else {
        invertedValue = '-' + item.value
      }

      return this.selected.includes(invertedValue)  
    }
  }
}
</script>

Answer №2

Method 1 - Using the change Event Handler

To implement the functionality, include a change event handler for the v-select component as shown below:

<v-select
  @change="onSelect"
  v-model="selected"
  :items="recipes"
  label="Select"
  multiple
  hint="Pick your meal"
  persistent-hint
  item-value="id"
  item-text="name"
></v-select>

In the event handler, disable items with different types based on the selected value:

methods: {
  onSelect(e) {
    if (e.length == 0) {
      this.recipes.forEach((item) => item.disabled = false)
    } else {
        let chosen = this.recipes.filter((item) => item.id==e[0])
        this.recipes.forEach((item) => {
          if (item.type != chosen[0].type) {
            item.disabled = true
          }
        })
      }
  }
}

Method 2 - Using a Watcher

Another approach is to add a watcher for the selected property:

watch: {
    selected: function (e) {
      if (e.length == 0) {
       this.recipes.forEach((item) => item.disabled = false)
      } else {
       let chosen = this.recipes.filter((item) => item.id==e[0])
       this.recipes.forEach((item) => {
         if (item.type != chosen[0].type) {
          item.disabled = true
         }
       })
     }
    }
  },

Answer №3

By utilizing a watcher for the selected array, it becomes possible to verify if the chosen recipes belong to the same category:

watch: {
    selected: function() {
      for (const index in this.recipes) {
        if (this.selected.length && this.recipes[index].type != this.recipes[this.recipes.findIndex(x => x.id === this.selected[0])].type) {
          this.recipes[index].disabled = true;
        } else {
          this.recipes[index].disabled = false;
        }
      }
    }

}

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 I write the code to enable dragging the button for navigating to the next page?

<a draggable="true" class="user" id="leonardo" ondragstart="dragUser(this, event)" aria-selected="undefined"> IPD</a> If I want the button to navigate to the next page when dragged, what code should I write? ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Minimize/Maximize Swagger Response Model Class View

After successfully integrating Swagger API documentation with my rest services, I encountered a challenge. The Swagger page appears too lengthy due to the numerous response classes in my project, requiring users to scroll extensively to find information. ...

Sending a JSON stringified JavaScript object to a server: A step-by-step guide

I am currently working with VB.Net and MVC 5. In my project, I have an object that I created using javaScript: var myEdits = { listOfIDs: [], listOfValues : [] }; My goal is to send this object to the controller an ...

Obtaining the data value from a style applied to a div element in an E-commerce platform like MyShop

I have recently started using MyShop for my online store at www.myshop.com. The programming language they use is quite different from what I am used to. For example, the total price in the basket.html script is displayed using the following code: <spa ...

Running globally installed node modules on Windows 7 is not supported

Note: Despite scouring various posts on this issue, I have not found a solution that works for me. That's why I am reaching out here. Problem: I am facing an issue while trying to set up the http-server package on my Windows 7 system using the comman ...

A guide on adding a personal library to Ember using npm

Despite the abundance of blog posts discussing it, I am still facing challenges in utilizing a custom library as a dependency for my ember application through npm. I have developed a WebGL library and successfully imported it into my Ember app by installi ...

Inserting data into a Textbox by clicking on a Div

I'm currently working on creating a wallpaper changer for my website. Right now, I'm looking to input the URL of a wallpaper into a text box when the corresponding DIV option in a CSS menu is clicked. Below is the JQuery I am using: $("div.bg8 ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

What is the best approach to managing a standard form in React without utilizing AJAX?

Trying to access an endpoint https://api.com/signup.ashx is causing CORS issues. I have been instructed to make the API call without using axios or fetch. Here's what I attempted: const handleSubmit = async (event) => { let error = false ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...

Is it possible to display Google pie charts when clicking on text or an image?

Having trouble setting up a link that triggers an onClick() action to generate a Google pie chart? Check out this example on JSFiddle. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="piech ...

Modifying the class of an HTML element using JavaScript

Is it possible to dynamically change the class of an HTML element based on a user's selection with a radio button? I am facing an issue where I receive the following error message: "Error: missing ) after argument list Source File: website Line: 1, C ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

Why does the page constantly redirect to the login screen when I refresh it?

Whenever I attempt to refresh the page or open a new tab on a secure page, it redirects me back to the login screen. Version Nuxt.js v2.9.1 @nuxtjs/module: 4.8.4 Secure Page middleware: ['auth'], Middleware of Auth Module Login Page middle ...

What is the best way to scale down my entire webpage to 65%?

Everything looks great on my 1920x1080 monitor, but when I switch to a 1024x768 monitor, the content on my webpage becomes too large. I've been manually resizing with CTRL+Scroll to reduce it to 65%, which works fine. Is there a code solution using CS ...

What is the best way to relocate an image or link using CSS?

I've been attempting to adjust the position of this image using CSS, but no matter how many times I try, it just refuses to budge. Can someone please help me troubleshoot what might be causing this issue? #yahoo1 { position: absolute; top: 100p ...