Managing router query parameters in Vue.js

Managing router query parameters in Vue.js

URL query parameters are a convenient way to store the state of a view so that the user can return to it using the back button after navigating away. This short article introduces a method to add parameters to the current URL.

Adding (or removing) query parameters can be achieved with the following method.

setQueryParam(key, value) {
      if (this.$route.query[key] === value) return
      const query = { ...this.$route.query }
      if (value) query[key] = value
      else delete query[key]
      this.$router.replace({ query })
},

Note the use of replace instead of push, which prevents adding new entries to the router history.