title: Vue.js: How to fire a watcher function when a component initializes
body: <p>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. </p>
  
  <p>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 <code>methods</code> object, and then calling that method in the watcher and the <code>mounted</code> hook. </p>
  
  <p>Here's an example:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>new Vue({ 
    el: '#app',
    data() {
      return {
        selectedIndex: 0,
      }
    },
    methods: {
      focusSelected() {
        this.$refs.input[this.selectedIndex].focus();
      }
    },
    watch: {
      selectedIndex() {
        this.focusSelected();
      }
    },
    mounted() {
      this.focusSelected();
    }
  })</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"&gt;&lt;/script&gt;
  &lt;div id="app"&gt;
    &lt;div v-for="i in 4"&gt;
      &lt;input ref="input"/&gt;
      &lt;button @click="selectedIndex = (i - 1)"&gt;Select&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Is there a way for me to be able to have the watcher fire when the component initializes?</p>