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>
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
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With