代码之家  ›  专栏  ›  技术社区  ›  Tom

在VueJS/VuetifyJS中切换开关时调用函数

  •  8
  • Tom  · 技术社区  · 7 年前

    我正在使用 VuetifyJS 对于VueJS,如果切换开关,我需要调用一个函数。如何做到这一点?

    模板:

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

    脚本:

    <script>
      export default {
        data () {
          return {
            switch1: false
          }
        }
      }
    </script>
    
    2 回复  |  直到 7 年前
        1
  •  20
  •   Mehul Prajapati    6 年前

    找到了另一个更好的解决方案 @change prop,它在每次切换开关时调用该方法。

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

    这是剧本,

    methods:{
        changeState(id) {
            console.log("Switch "+id);
            // Do stuff
        }
    }
    
        2
  •  7
  •   Vamsi Krishna    7 年前

    您可以设置 watcher 在…上 switch1 数据属性如下:

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

    v-model 属于 v-switch 是必须的 开关1 ,每当开关打开/关闭 开关1 使用更改的 newValue

    这是一个 codepen