What are the steps to require v-switch in Vuetify?

I am working with three v-switch elements, each of them is tied to the switch1 property.

Whenever I click on a v-switch, it either adds or removes a value from switch1.

Is there a way to make a v-switch mandatory? In other words, it should not be possible to uncheck all of them. At least one must always be selected.

I was thinking of implementing an event that checks if switch1 will be an empty array, and then cancels the switch click.

I attempted to achieve this using the change event, but the e parameter comes as a Boolean instead of the event object.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      switch1: ['val1', 'val2', 'val3'],
      change: (e) => { console.log({ e }) }
    }
  },
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec8c1c0daee9a80d6">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88e8d9d8c919e81b8cad6c9d6c9cc">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet"/>

<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1066657550223e68">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592f2c3c2d303f20196b776877686d">[email protected]</a>/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-container class="px-0" fluid>
      {{ switch1 }}
      <v-switch
        v-model="switch1"
        label="val1"
        value="val1"
        @change="change($event)"
      ></v-switch>
      <v-switch
        v-model="switch1"
        label="val2"
        value="val2"
        @change="change($event)"
      ></v-switch>
      <v-switch
        v-model="switch1"
        label="val3"
        value="val3"
        @change="change($event)"
      ></v-switch>
    </v-container>
  </v-app>
</div>

Answer №1

In order to handle the situation where none of the switches are in a true state, I would utilize a watcher to monitor the state of the switches and if all of them are false, I would automatically set the first one to true.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      switch1: ['val1', 'val2', 'val3'],
    }
  },
  methods: {
    change: (e) => {
      /*console.log({
        e
      })*/
    }
  },
  watch: {
    switch1(newVal, oldVal) {
      if (newVal.length) {
        this.switch1 = newVal
      } else {
        setTimeout(() => this.switch1 = oldVal)
      }
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57313839231763792f">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="106665756479766950223e213e2124">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d3d0c0e5978bdd">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b0b3a3b2afa0bf86f4e8f7e8f7f2">[email protected]</a>/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-container class="px-0" fluid>
      {{ switch1 }}
      <v-switch v-model="switch1" label="val1" value="val1" @change="change($event)"></v-switch>
      <v-switch v-model="switch1" label="val2" value="val2" @change="change($event)"></v-switch>
      <v-switch v-model="switch1" label="val3" value="val3" @change="change($event)"></v-switch>
    </v-container>
  </v-app>
</div>

I have also made an edit to the snippet to provide a more general solution. I appreciate the feedback on moving the @change event from the data to the methods. Thank you, @JonSud!

Answer №2

Although it doesn't directly answer the question, one approach is to validate a group of switches and show an error message when none of the switches are active.

To achieve this, we can create an Array called switches to keep track of the status of each switch.

By using a computed property called noneSelected, we can filter the values in the Array based on their truthiness. If the length of the filtered Array is zero (0), we can use v-if to display the error message.

Vue.config.productionTip = false;
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      switches: [false, false, false]
    }
  },
  computed: {
    noneSelected() {
      return this.switches.filter(x => !!x).length === 0;
    }
  },
  methods: {
    change: (e) => { console.log('event', e)}
  }
});
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a1c15140e3a4e5402">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15636070617c736c55273b3">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet"/>


<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91e7e4f4d1a3bfe9">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a0a3b3a2bfb0af96e4f8ae">[email protected]</a>/dist/vuetify.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-container class="px-0" fluid>
      {{ switches }}
      <p v-if="noneSelected" style="color: red">At least one switch needs to be active.</p>
      <v-switch
        v-model="switches[0]"
        label="val1"
        @change="change($event)"
      ></v-switch>
      <v-switch
        v-model="switches[1]"
        label="val2"
        @change="change($event)"
      ></v-switch>
      <v-switch
        v-model="switches[2]"
        label="val3"
        @change="change($event)"
      ></v-switch>
    </v-container>
  </v-app>
</div>

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

Organize an array of objects in JavaScript into a structure with nested children

I am facing a challenge with organizing an array of objects based on parentId and sort values. I need to create a nested array with 'children' and ensure proper sorting. Consider the following data: [{ id: 1, sort: 2, parentId: null ...

Guidelines for choosing input using jQuery

I am looking to retrieve the value of an input using jQuery. Specifically, I need to extract the value of a hidden input with name="picture" when the user clicks on the حذف این بخش button by triggering the function deleteDefaultSection( ...

What is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance ...

Mastering the flow of control in Node.js programs

Attempting to grasp control flow within Node.js applications. Specifically, does control loop back to the original function once the callback method completes, similar to a callback stack in recursive calls? A simple program was crafted to make a GET call ...

What is the process for inserting text into a Word document using the Google Docs API?

Struggling to generate a Word document with text and images, but the text refuses to show up. My document remains blank, even though there seems to be no issue with my code. Any guidance on what I might be missing would be greatly appreciated. gapi.client ...

Converting individual items into an array of objects within a JSON file for export

Currently, I am utilizing node.js and my loop is producing a single object that looks like this: Output { prop1:"val1", prop2:"val2", .. } This object is generated every 10 seconds and it may contain different keys and values each time. To write t ...

The PHP script receives an empty string value passed from JavaScript

I am struggling to pass a string from my JavaScript code to my PHP code. Here is the code snippet that triggers when I hit Enter in a text input: $('#user').keypress(function(e) { if(e.which == 13) { var val = $(this).val(); ...

Embrace the flexibility of using Next.js with or without Express.js

Recently, I started the process of migrating a project from create-react-app to next.js. However, I am facing uncertainty when it comes to migrating the backend of the project. Currently, my backend is built with an express server. In next.js, there are p ...

What is the most effective way to extract the output from a JSONP request and utilize it beyond the

I have a function that is working well. I had to use JSONP to handle cross-domain issues, and I also wrote an HTTP module to change the content-type. However, I did not include a callback name in the URL. function AddSecurityCode(securityCode, token) { va ...

Connecting a pre-existing Angular 2 application to a Node.js server: A step-by-step guide

I am currently working on an Angular 2 application with the following structure : View Structure of my Angular app Furthermore, on the server side : View Structure of server app I have noticed that there are two module dependencies folders, but I am un ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Serve static files using ExpressJS when a post request is made

My Express server is set up to serve static files for my website and it's working fine: var express = require('express'); var app = express(); var path = require('path'); var p = path.join(__dirname, '../web/public'); app ...

Arrays contain multiple elements, not just a single item

Is it possible to display multiple objects in one container? For instance, I have an array let array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; array.forEach((item, index) => ( <div> <div> item 1, 2, 3 </div> <div> item 4, 5, 6 </div ...

Establishing numerous websocket connections within a singular application

I am looking to conduct load testing on our websocket service. Is there a method to establish multiple websocket connections from one workstation? My attempt with npm ws and websocket modules in conjunction with NodeJS was successful for a single connecti ...

Retrieving specific object properties within an Angular 2 and Ionic 2 form

Within the @Page, I have a few select inputs. In addition to storing the value of the selected option, such as {{project.title}}, I also require the ability to return another selected object property, such as {{project.id}} or even the entire object. When ...

Express.js returning unexpected results when calling MySQL stored procedures

I've encountered a strange issue with a stored procedure called getUsers in MYSQL. When I execute the procedure in phpmyadmin, it returns a table of users with their data perfectly fine. However, when I try to call the same procedure from my Node.js a ...

Tips for postponing the execution of following tasks until the completion of the setState and ensuring that they are reliant on

I'm encountering an issue with the useEffect hook in my React app that uses useState. Here's the code snippet: const [jobTypes, setJobTypes] = useState([]); const getJobTypes = async () => { try { const response = await fetch(&a ...

Is it possible for the connectedCallback() method within a Custom Component to have varying interpretations based on the specific context in which it is implemented?

I have recently developed a Custom Component that incorporates a Vue instance: class ContentCardExample extends HTMLElement { connectedCallback() { const card = document.createElement('div'); card.setAttribute("id", "app") card.i ...

Avoid showing an image when it is outside the div container

Within a single div, I have an assortment of images that are dynamically repositioned using JQuery. $("#"+carElem).css({"left": pos.left+50 +"px"}); I am currently utilizing absolute positioning (although relative positioning yields the same outcome). Is ...