Set URL Query Params In Vue 2 Using Vue-Router
Short tutorial on how to set URL query params in Vue with Vue-Router using router-link, router.push and router.replace
This article will show you three ways how to set URL Query or URL params in Vue 2 using Vue-Router.
What is URL query?
In simple words, a URL query is a key-value pair that we see at the end of a URL after the question mark sign (?). It is a portion of a URL that is used to pass data to the back-end.
You can see it when we do a search on a website, like YouTube or Google.
https://www.google.com/search?q=query
In Vue, there are 3 ways to set query params in a URL:
- router-link
- router.push()
- router.replace()
Let's see each one with an example.
Set Query params in Vue 2
In <router-link /> we can use the :to="" prop to set our query params. The <router-link /> to create anchor tags for declarative navigation in Vue.
Example:
<router-link :to="{ path: '/gallery', query: { id: 1 } }">gallery</router-link>
Here we have set a query with an id:1. Check the example below to see the code in action.
router.push() to dynamically add query params in URL in Vue
router.push let us dynamically set query params in a URL. It pushes a new entry into the history stack, so whenever a user clicks the back button in the browser it returns back to the previous page.
Syntax:
router.push(location, onComplete?, onAbort?)
Example:
this.$router.push({ path: "/gallery", query: { id: 1 } });
If you want to set multiple queries you can pass it like this:
this.$router.push({ path: "/gallery", query: { id: 1, name: "parker"} } });
Note:
You can access the router instant as $router. Therefore, you can call
this.$router.push()
Set query params in Vue using router.replace()
router.replace() is the same as router.push() , the only difference is that it navigates to a different route without pushing a new history entry. It just replaces the current entry.
So you cannot press the back button in your browser to return to the previous page.
Example:
this.$router.replace({ path: "/gallery", query: { id: 1 } });
DEMO
Related Topics:
How To Redirect To External Url In Vue
How To Call A Function In VUE Template?
Include External CSS File In Vue.Js Component
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
