Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this:

<form class="search-form" @submit.prevent="search">
    <div class="form-group">
        <input type="text" class="form-control" v-model="term" placeholder="Search">
    </div>
</form>

Below is my script implementation:

<script>
  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 => {
          this.$router.push({query: { 'term' : this.term}})
          this.items = response.data.collection.items
        })
        .catch(error => {
          return error
        })
      }
    }
  }
</script>

The main goal of my code is to accomplish the following tasks:

  1. User submits the form, which triggers the search() function. The URL gets updated with the query parameter, for example, /search?term=<term>. However, I am facing an issue where the search() function runs twice in this scenario.
  2. User conducts multiple searches and then clicks the back button. The search field updates in the form automatically and initiates the search. Similar to the first point, the search() function seems to run twice here as well.
  3. User manually inserts a query parameter in the URL bar. The search field in the form populates accordingly and executes the search successfully. This functionality is working seamlessly.

The repeated execution of the search() function stems from the watch() method, responsible for monitoring changes in the URL bar. However, merging this mechanism effectively with the search() function remains a challenge for me.

Answer №1

When using the watch method, you can compare a new value with an old value and only trigger a search when there is a difference between the two.

watch: {
  '$route.query.term'(newVal, oldVal) {
    if (newVal != oldVal) {
      this.term = this.$route.query.term
      this.search()
    }
  }
},

To ensure that the search is only triggered once for each case, it's advisable to separate the button click handler from the actual search call.

<script>
  export default {
    data() {
      return {
        term: this.$route.query.term,
        items: []
      }
    },
    created() {
      if (this.term !== null) {
        this.performSearch()
      }
    },
    watch: {
      '$route.query.term': {
        handler: function(newVal, oldVal) {
          if (newVal !== oldVal) {
            this.term = this.$route.query.term
            this.performSearch()
          }
        },
        immediate: true 
      }
    },
    methods: {
      search: function () {
        // This is called when the user clicks the search button
        this.$router.push({query: { 'term' : this.term}})

      },
      performSearch() {
        // Perform the actual search
        window.axios.get('/images/search', {
          params: {
            term: this.term
          }
        })
        .then(response => {
          this.items = response.data.collection.items
        })
        .catch(error => {
          return error
        })
      }
    }
  }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pause the jquery script when a key is pressed

Currently, I have a script that loads a php file within a div and automatically refreshes every 5 seconds. Check out the code below: $("#load_timeout").load("time_out.php"); var refreshId = setInterval(function() { $("#load_timeout").load('time_o ...

Having trouble getting async and await to function properly

Why is my code not waiting for validation and running the else part immediately? Can you help me find the mistake? async validateBeforeSubmit(event) { await this.$validator.validateAll().then(result => { if (result) { ...

Guide on converting a GraphQL request string into an object

Seeking assistance with intercepting and parsing GraphQL queries/mutations from a POST request body in an Apollo lambda server environment running on Node.js. The requests do not come in JSON format, but as GraphQL query language. I have been unable to fi ...

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Preventing clicks within an iframe

Within an iframe, I have HTML content that includes hyperlinks. I need to prevent clicks on these hyperlinks. I managed to accomplish this using jQuery as shown below. However, I prefer not to use jQuery for this task. How can I achieve the same result ...

Issues with Jquery Ajax POST request not resolving

Can you explain why the success code is not being executed in this request? $(document).ready(function(){ var post_data = []; $('.trade_window').load('signals.php?action=init'); setInterval(function(){ ...

While constructing my Node.js application, I encountered an issue related to the vue-cli-service

I encountered an issue while attempting to build my nodejs app using "vue-cli-service". The error message is as follows: 20 error code ELIFECYCLE 21 error errno 1 22 error @ozu/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e0 ...

Experiencing difficulties establishing a connection between the React client and Node.js server using SocketIO

I am currently getting familiar with socketIO and have successfully set up a basic nodejs server. However, I am facing an issue where my nextJS app is unable to connect to the server as expected. Despite no errors being displayed, the messages that should ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...

Strategies for addressing input range slider cross browser compatibility issues

I have encountered an issue with the slider track while using a customized range slider with CSS. For Mozilla, I utilized the selector for progress (-moz-range-progress) and for IE I used -ms-filler-lower and -ms-filler-upper. Although it works well for b ...

When executed on the node REPL, lodash.sortBy will update the lodash value

When I access the node REPL, the following happens: > _ = require('lodash'); > // it displays the whole lodash object > _.sortBy(['1234', '123'], function (element) { return element.length; }); > [ '123&apos ...

Passing an array from the PHP View to a JavaScript function and plotting it

Greetings, I am currently facing the following tasks: Retrieving data from a database and saving it to an array (CHECK) Sending the array from Controller to View (CHECK) Passing that array to a JavaScript function using json_encode (CHECK) Plotting the ...

Try utilizing the 'id name ends with' parameter within the on() function for creating dynamic bindings

I need help with dynamically binding the change event to multiple select input fields that are generated within my form. The item field is generated with IDs like: id="id_form-0-item" id="id_form-1-item" id="id_form-2-item" ... Although I have attempte ...

Is Python a suitable programming language for developing applications on a Raspberry Pi device?

I'm diving into the coding world for the first time and I have a project in mind - controlling my RC car with my smartphone using a Raspberry Pi 3. Research suggests that I should use Node.JS and JavaScript to create the app, but I'm wondering if ...

Encountering an error in Vue.js Meteor: Unable to read properties of undefined when trying to access 'find'

Recently, I've been following a tutorial at However, even when trying to install the default Vue Meteor app, I encounter an error. meteor: { $subscribe: { 'experiments': [], }, experiments () { return Experiments.find({}).fetch(); }, } ...

Tips for resetting input and select values in VUE

In my VUE application, I have an input and a select that are displayed based on the selection of a previous input. When I enter values and change the initial input selection, I hide the second input and select to reset the form. However, even after resetti ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

The Functionality of Accordions

I have created a responsive accordion script that functions smoothly and allows for easy access to content within each drawer. Unlike many accordions, this one does not cause issues with positioning after opening. The code I am using includes a toggle acti ...