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

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 });
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <div v-for="i in 4">
    <input ref="input"/>
    <button @click="selectedIndex = (i - 1)">Select</button>
  </div>
</div>

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;
    }
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)