Query路由传参
编程式导航 使用router push 或者 replace 的时候 改为对象形式新增query 必须传入一个对象
// item 必须是对象
const toDetail = (item: Item) => {
router.push({
path: '/reg',
query: item
})
}
接收参数
使用 useRoute 的 query
import { useRoute } from 'vue-router';
const route = useRoute()
console.log(route.query?.name)
Params路由传参
使用Params必须使用对象形式,且使用name,不能path, 然后传入params
const toDetail = (item: Item) => {
router.push({
name: 'Reg',
params: item
})
}
接收参数
import { useRoute } from 'vue-router';
const route = useRoute()
console.log(route.params?.id);
动态路由传参
很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数
**路径参数 用冒号 :**表示。当一个路由被匹配时,它的 params 的值将在每个组件
const routes:Array<RouteRecordRaw> = [
{
path:"/",
name:"Login",
component:()=> import('../components/login.vue')
},
{
//动态路由参数
path:"/reg/:id",
// 加上路由参数之后不能直接访问/reg 会返回404,必须加上参数
name:"Reg",
component:()=> import('../components/reg.vue')
}
]
// 传递参数
const toDetail = (item: Item) => {
router.push({
name: 'Reg',
params: {
id: item.id
}
})
}
// 接收参数
import { useRoute } from 'vue-router';
import { data } from './list.json'
const route = useRoute()
const item = data.find(v => v.id === Number(route.params.id))
区别
query 传参配置的是 path,而 params 传参配置的是name,在 params中配置 path 无效
query 在路由配置不需要设置参数,而 params 必须设置(动态路由中添加字段)
query 传递的参数会显示在地址栏中
params传参刷新会无效,但是 query 会保存传递过来的值,刷新不变 ;
路由配置
将 props 传递给路由组件
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const routes = [{ path: '/user/:id', component: User }]
替换成
const User = {
// 请确保添加一个与路由参数完全相同的 prop 名
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const routes = [{ path: '/user/:id', component: User, props: true }]
对于有命名视图的路由,你必须为每个命名视图定义props配置:
const routes = [
{
path: '/promotion/from-newsletter',
component: Promotion,
props: { newsletterPopup: false }
}
]
也可以设置为对象
const routes = [
{
path: '/promotion/from-newsletter',
component: Promotion,
props: { newsletterPopup: false }
}
]
函数模式
const routes = [
{
path: '/search',
component: SearchUser,
props: route => ({ query: route.query.q })
}
]
