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

Designing a photo frame slider for a unique touch

My skills in javascript and jQuery are limited, but I am looking to create a customizable slider. While exploring options like Flexslider (), I found it challenging to meet the following specifications: Eliminate color gaps between thumbnails Enable thu ...

Retrieve posts from Angularjs

I am attempting to fetch tweets from a Twitter account using only AngularJS without the use of PHP or any other programming language. I have made several attempts but have not been successful. Additionally, I must utilize the 1.1 version of the Twitter A ...

Steps to turn off the automatic completion feature for orders in WooCommerce on your WordPress website

Looking for assistance with changing the order status from completed to processing. When an order is placed, it automatically goes to completed status which is not the desired outcome. The status should change based on the virtual product purchased. I wou ...

Error: The module you are trying to import from the package is not found. Please check the package path and make sure that

I encountered an issue when trying to compile a code in Reactjs. As a beginner in Reactjs, I'm struggling with this. Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-rea ...

MS Edge modifies the attribute's empty value to 1

I have written a JavaScript code to extract values from a list, but in the Windows Edge browser, it returns a value of 1 even when the actual value of the <li> tag is blank. For example: HTML Code <ul> <li value="">Test 1</li&g ...

Tips for aligning placeholder and text at the center in a React Material UI TextField

Existing Layout: https://i.stack.imgur.com/Zv4Tg.png Desired Layout: https://i.stack.imgur.com/Xuj6O.png The TextField element is displayed as follows: <TextField multiline={false} autoFocus placeholder={props.defaultAmt} ...

Adding a child node before an empty node in Chrome with JavaScript Rangy

When attempting to insert a node before an empty element at the start of another element, a problem was noticed. Here is the initial setup: <p>|<span />Some text</p> By using range.insertNode() on a Rangy range to add some text, Chrome ...

Using ngFor directive to iterate through nested objects in Angular

Receiving data from the server: { "12312412": { "id": "12312412", "something": { "54332": { "id": "54332", "nextNode": { "65474&q ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

What causes the order of `on` handler calls to be unpredictable in Angular?

Below is the code snippet I have been working on function linkFunc(scope, element, attr){ var clickedElsewhere = false; $document.on('click', function(){ clickedElsewhere = false; console.log('i ...

"Patience is key as you wait for various pictures to fully

I have a collection of images to load, all organized in an Array. As each image is loaded, I increase a counter within a loop. Once this counter matches the length of my images Array, I intend to remove the loading indicator. For some reason, it's ...

Retrieving PHP data with jQuery

Isn't it interesting that I couldn't find anything on Google, but I believe you can assist me. I have a Table containing different accounts. Upon clicking on a specific row, I want another table related to that account to slide in. This secondary ...

Populating Dropdown list with values based on input provided in Textbox

Can you assist me in finding the solution to this issue? I have a TextBox and a DropDown list. For example, if I type "Anu" into the textbox, I want it to populate the dropdown list based on the text entered. How can I achieve this? I am working with vb. ...

Exploring the world of handling GET and POST parameters in Node.js with

As someone who is new to Node/Express, I've noticed that GET parameters can be captured using the following syntax: app.get('/log/:name', api.logfunc); For POST requests, it can be done like this: app.post('/log', ... (with for ...

Is an Ajax powered loading feature used in transitions between pages?

I recently came across this interesting website: It appears that they have implemented a clever technique where new content is dynamically loaded using AJAX, giving the impression of seamless navigation. Additionally, they have succeeded in hiding the bro ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

The modal template in Angular UI is not displaying properly with Bootstrap styling

I've been working on displaying a modal template when a row is selected on a table. The issue I'm facing is that upon clicking a row, a 2px thick black shadowed line appears, which seems to represent the modal but doesn't display its conten ...

Problem with retrieving information from an array of objects - Vue.js / accessing API / utilizing axios / implementing proxy

Currently, my project involves using Vue.js to connect to an API and retrieve data using axios with a proxy. I am facing difficulty accessing the property of an object nested within multiple arrays. Below are more details: View Global details Property I& ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

Navigating the Foundation Topbar - Should I Toggle?

Is there a simpler way to achieve the navigation I desire, similar to the switcher for uikit? Instead of using data-toggler on each tag in my top bar, is there an easier method where I can click links in my top bar to display different content without go ...