34

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.

The watcher does not fire when the component initializes since the property being watched technically hasn't changed yet. So, I end up putting the function in the methods object, and then calling that method in the watcher and the mounted hook.

Here's an example:

new Vue({ 
  el: '#app',
  data() {
    return {
      selectedIndex: 0,
    }
  },
  methods: {
    focusSelected() {
      this.$refs.input[this.selectedIndex].focus();
    }
  },
  watch: {
    selectedIndex() {
      this.focusSelected();
    }
  },
  mounted() {
    this.focusSelected();
  }
})
<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>

Is there a way for me to be able to have the watcher fire when the component initializes?

1 Answer 1

62

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;
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the second solution will be fired when the component is created, but before it is mounted
The code above is written for vue2. Here are the docs for vue3: vuejs.org/api/component-instance.html#watch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.