Prevent switch toggle and show alert message v-switch in Vuetify

Viewed 971

I'm facing a problem to prevent the toggle for the v-switch and show an alert message. Here is Codepen example

If I add CSS to prevent the toggle, then click event is not working

.v-input--switch {
  pointer-events: none;
}

Also, if I add disabled prop to switch, then click event is not working

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      switch1: true,
       snackbar: false
    }
  },
  methods:{
    showALert(){
      this.snackbar = true;
    }
  }
})
.v-input--switch .v-input--switch__thumb {
  color: black !important;
}

.v-input--switch .v-input--switch__thumb.primary--text {
  color: black !important;
}

.v-input--switch .v-input--switch__track.primary--text {
  color: rgba(0, 0, 0, 0.38) !important;
}

.v-input--switch.v-input--is-disabled:not(.v-input--is-dirty) .v-input--switch__thumb {
  color: black !important;
}

.v-input--switch .v-input--switch__thumb:after {
  content: "£";
  color: #fff;
}

//.v-input--switch {
 // pointer-events: none;
//}
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.3.14/dist/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.3.14/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-container class="px-0" fluid>
      <v-switch :ripple="false" flat @change="showALert"></v-switch>
      <v-snackbar v-model="snackbar" bottom right>
        This has been set to Historical Mode
        <template v-slot:action="{ attrs }">
          <v-icon v-bind="attrs" color="white" small @click="snackbar = false">
            mdi-close
          </v-icon>
        </template>
      </v-snackbar>
    </v-container>
  </v-app>
</div>

Can someone help me with this? Any solutions would be appreciated.

1 Answers

You can use the readonly prop of the v-switch which prevents toggling of the switch when clicked. You can also add @click directly on v-switch to handle whatever behavior you want to happen when the switch is clicked like showing an alert or validating a value before toggling the switch programmatically.

  <v-switch @click="showALert" readonly></v-switch>
Related