路由传参:六种方法
<li v-for="article in articles" @click="getDescribe(article.id)">
<router-link to="/route/routeOne/参数">路由传参</router-link>
1,router-link to = '/' 字符串传参
通过router-link to传值::to="/route/${name}"(动态传参)`
// 路由配置
path: '/route/:name'
// 在传参的页面中
<router-link :to="/route/${name}">路由传参</router-link>
// 在接受传参的页面中
let name = this.$route.params.name
注:此方法传参,页面刷新数据不会丢失
2,router-link to = {path,query} 通过对象path传参
通过router-link to传值::to = {path:'route', query:{code:1}}
// 路由配置
path: '/route'
// 在传参的页面中
<router-link :to="{ path: '/route', query: { code: 1 } }">路由传参</router-link>
// 在接受传参的页面中
let code= this.$route.query.code
注:查询参数搭配query,页面刷新数据不会丢失
3,router-link to = {name,params} 通过对象name传参
通过router-link to传值::to = {name:'route', params:{code:1}}
// 路由配置
name: 'route'
// 在传参的页面中
<router-link :to="{ name: 'route', params: { code: 1 } }">路由传参</router-link>
// 在接受传参的页面中
let code= this.$route.params.code
注:查询参数搭配params,页面刷新数据会丢失
点击数据时,传参数据不会实时更新,除非该组件被重新渲染
4,路由配置传参
1, 路由的配置:
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
2,要传参的页面中
methods:{
getDescribe(id) {
//直接调用$router.push 实现携带参数的跳转
this.$router.push({
path: `/describe/${id}`,
})
}
- 在对应的页面接受 id 路由参数
let id =this.$route.params.id
命名路由搭配params,刷新页面参数不会丢失
5,通过路由 path query 来传参,路径不需要配置
1,对应路由配置:
{
path: '/describe',
name: 'Describe',
component: Describe
}
2,父组件:使用path来匹配路由,然后通过query来传递参数
这种情况下 query传递的参数会显示在url后面?id=?
this.$router.push({
path: '/describe',
query: {
id: id
}
})
3,对应子组件: 这样来获取参数
this.$route.query.id
命名路由搭配query,刷新页面参数会丢失
附:路由的写法:
@click="pushState('/four')"
pushState(route) {
this.$router.push(route);
}
6,通过属性 name params来传参
1,对应路由配置:
注:这里可以添加:/id 也可以不添加,不添加数据会在url后面显示,并且数据就不会显示
{
path: '/describe',
name: 'Describe',
component: Describe
}
2,父组件中:通过路由属性中的name来确定匹配的路由,通过params来传递参数。
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
3,子组件中: 这样来获取参数
let id = this.$route.params.id
命名路由搭配params,刷新页面参数会丢失
点击数据时,传参数据不会实时更新,除非该组件被重新渲染
但是,我们可以通过特殊方法,刷新时候,还能获取到传过来的参数
// 对应路由配置:
{
path: '/describe/:obj',
name: 'Describe',
component: Describe
}
// 父组件传值
this.$router.push({
name: 'Describe',
params: {
obj: JSON.stringify({
id: id,
}),
}
})
// 子组件接受值
let id = JSON.parse(this.$route.params.obj).id
网友评论