Vue.js: How to fire a watcher function when a component initializes

前端 未结 1 1265
一整个雨季
一整个雨季 2021-02-19 06:29

Sometimes I need to call some function in response to a change in a data property. But, I also need that function to fire for the initial value of the data property.

Th

1条回答
  •  难免孤独
    2021-02-19 06:39

    Watchers in Vue have an option to provide an immediate value:

    Passing in immediate: true in the option will trigger the callback immediately with the current value of the expression

    In this case, you could set a watcher in the mounted hook:

    new Vue({ 
      el: '#app',
      data() {
        return {
          selectedIndex: 0,
        }
      },
      mounted() {
        this.$watch('selectedIndex', (i) => {
          this.$refs.input[i].focus();
        }, { immediate: true });
      }
    })
    
    


    You could also specify the immediate option for a watcher in the watch object like so:

    watch: {
      foo: {
        immediate: true,
        handler(value) {
          this.bar = value;
        }
      }
    }
    

    0 讨论(0)
提交回复
热议问题