title: Vue.js - search form with query parameters
body: <p>I am using Vue.js 2.6 with the <code>vue-router</code> component. I have a search form as follows:</p>
  
  <pre><code>&lt;form class="search-form" @submit.prevent="search"&gt;
      &lt;div class="form-group"&gt;
          &lt;input type="text" class="form-control" v-model="term" placeholder="Search"&gt;
      &lt;/div&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>And here is my script:</p>
  
  <pre><code>&lt;script&gt;
    export default {
      data() {
        return {
          term: this.$route.query.term,
          items: []
        }
      },
      created() {
        if (this.term != null) {
          this.search()
        }
      },
      watch: {
        '$route.query.term'() {
          this.term = this.$route.query.term
          this.search()
        }
      },
      methods: {
        search: function () {
          window.axios.get('/images/search', {
            params: {
              term: this.term
            }
          })
          .then(response =&gt; {
            this.$router.push({query: { 'term' : this.term}})
            this.items = response.data.collection.items
          })
          .catch(error =&gt; {
            return error
          })
        }
      }
    }
  &lt;/script&gt;
  </code></pre>
  
  <p>What I am trying to achieve with this code is the following:</p>
  
  <ol>
  <li>User submits form, the <code>search()</code> function is called. The URL is updated with the query param, e.g. <code>/search?term=&lt;term&gt;</code>. <strong>This is working but the <code>search()</code> function is being called twice.</strong></li>
  <li>User carries out several searches, then presses the back button. The search field in the form is updated and the search is carried out. <strong>This is working but the <code>search()</code> function is being called twice.</strong></li>
  <li>User manually enters query param in the URL bar. The search field in the form is populated and the search is carried out. <strong>This is working.</strong></li>
  </ol>
  
  <p>Where the <code>search()</code> function is being called twice, this is due to the <code>watch()</code> function, which is designed to watch changes to the URL bar. I am not sure how to combine this function correctly with the <code>search()</code> function.</p>