Search code examples
javascriptvue.jstogglevuetify.js

Call function if switch gets toggled in VueJS/VuetifyJS


I'm using VuetifyJS for VueJS and I need to call a function if the switch gets toggled. How to do that?

Template:

 <v-container fluid>
    <v-switch :label="`Switch 1: ${switch1.toString()}`" v-model="switch1"></v-switch>
  </v-container>
</template>

Script:

<script>
  export default {
    data () {
      return {
        switch1: false
      }
    }
  }
</script>

Solution

  • You can set up a watcher on switch1 data property as follows:

    <script>
      export default {
        data () {
          return {
            switch1: false
          }
        },
        watch: {
          switch1(newValue){
            //called whenever switch1 changes
            console.log(newValue);
          }
        }
      }
    </script>
    

    Since the v-model of v-switch is bound to switch1 , whenever the switch is toggled on/off the watch handler of switch1 gets called with the changed newValue

    Here is a codepen