Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 906
Tom Avatar asked Apr 02 '18 09:04

Tom


2 Answers

Found another better solution to use @change prop, Which calls the method every time the switch is toggled.

    <v-switch
        :input-value="true"
        @change="changeState(item.id)"
    ></v-switch>
    <v-switch
        :input-value="true"
        @change="changeState(item.id)"
    ></v-switch>

Here's script,

methods:{
    changeState(id) {
        console.log("Switch "+id);
        // Do stuff
    }
}
like image 143
Mehul Prajapati Avatar answered Nov 05 '22 19:11

Mehul Prajapati


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

like image 35
Vamsi Krishna Avatar answered Nov 05 '22 19:11

Vamsi Krishna