Home > Article > Web Front-end > How to get address bar parameters in Vue3
Vue3 has two ways to obtain address bar parameters: query parameters and path parameters.
Vue3 obtains the address bar parameters from the routing router. The query parameters and path parameters are obtained in different ways.
For example, the address http://127.0.0.1:5173/?code=123123,
If we want to get the code parameter, we can get it from the router. Note that it is route. query
First you need to define the route in router/index.js
import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: () => import('../views/home.vue') }, ] }) export default router
Then you can get the query parameters through useRouter in the component
<script setup> import {useRouter} from 'vue-router' const { currentRoute } = useRouter(); const route = currentRoute.value; onMounted(()=>{ let code=route.query.code console.log('code', code) }) </script>
The path parameter refers to the parameters that are spliced in the address bar.
For example, the address http://127.0.0.1:5173/123123
The last 123123 is the parameter.
This kind of parameter must first be defined in the route, and the parameter must be named in the route. In the following code: code is to name a path parameter code
First it needs to be defined in router/index.js Good routing and path parameters
import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/:code', name: 'home', component: () => import('../views/home.vue') }, ] }) export default router
Then you can get the parameters through the route useRouter in the home.vue component. Note that route.params
<script setup> import {useRouter} from 'vue-router' const { currentRoute } = useRouter(); const route = currentRoute.value; onMounted(()=>{ let code=route.params.code console.log('code', code) }) </script>
Entry pageApp.vue
must define the router-view
tag. You cannot simply introduce the home component defined above directly into App.vue
, if it is introduced directly, it will not be a route, so the routing parameters cannot be obtained through useRouter
The following error example:
<template> <div id="app"> <home></home> </div> </template> <script setup> import home from './views/home.vue'; </script>
The correct one should be to use router-view
tag
<template> <div id="app"> <router-view></router-view> </div> </template> <script setup> </script>
The above is the detailed content of How to get address bar parameters in Vue3. For more information, please follow other related articles on the PHP Chinese website!