Detailed Solution of Vue Routing (Params and Query)
Preface:
Route parameter transmission includes parAMS parameter transmission and Query parameter transmission
Params passing parameters is similar to a POST request in a network request. Parameters passed by Params are not displayed in the address bar (but cannot be refreshed). Params can only be used with name. If path is provided, params is invalid.
Query parameter passing is similar to the GET request in a network request. The parameters passed by query are concatenated in the address bar. Name = xx). Query is flexible and can be used with either Path or name (which can be tested in person).
What is name? Name is the alias of path during route configuration for easy use. Note that “the path displayed in the address bar is always the value of path”
const routes = [
{
path: '/login',
component: Login
},
{
path: '/home',
name: 'home',
component: Home
}
]
Copy the code
The most important point of name is to coordinate with Params to pass routing parameters. Let’s take a look at an example: when we log in we need to display the user name on the home page. Of course there are many methods such as localStorage, sessionStorag, central event bus, but we need to learn the route to pass parameters.
-
Method 1: Upload parameters through Params
-
Programmatic:
-
data:{ username: '' }, login() { ... $router. Push ({name: 'home', // note that path params: {username: this.username},})}Copy the code
-
-
Declarative:
-
<router-link :to="{ name: 'home', params: { username: username } }"> Copy the code
-
-
Values: this $route. Params. The username
-
-
Method 2: Use query to send parameters
-
Programmatic:
-
data:{ username: '' }, login() { ... this.$router.push({ path: '/home', query: { username: this.username }, }) } Copy the code
-
-
Declarative:
-
<router-link :to="{ path: '/home', query: { username: username } }"> Copy the code
-
-
Values: this $route. The query. The username
-
After params uploads the parameter, refreshing the page will lose the parameter. Therefore, route parameters must be changed to'/login/:username'
(Officially called dynamic routing)
const routes = [
{
path: '/login',
component: Login
},
{
path: '/home/:username',
name: '/home',
component: Home
}
Copy the code
But this is not like a POST request, where it replaces the received parameters as addresses.
Params: {username: ‘admin’} params: {username: ‘admin’}http://localhost:8080/home/admin
conclusion
- Using the login example, if the username is not sensitive information, it can be placed directly in the address bar (using the query parameter)
- Why not use Params to pass the parameter? Cannot refresh because params pass parameter. The user name will also be displayed in the address bar if the address needs to be modified
\