$route
和 $router
的区别
$route
是路由信息对象,包括path
,params
,hash
,query
,fullPath
,matched
,name
等路由信息参数$router
是路由实例对象包括了路由的跳转方法,钩子函数等
动态路由
定义动态路由:
(1) params 方式
- 路由配置:
/about/:id
- 传值:
/about/123
具体配置
// 路由表中的配置
import About from '@/components/About.vue'
const router = new VueRouter({
routes: [
{path: '/about/:id', component: About}
]
})
// 组件中传值 假设id是5
<router-link :to="`/detail/${id}`">跳转详情列表</router-link>
还可以像如下跳转
<router-link :to="{name: 'detail', params: {id: 5, title: '介绍'}">
跳转详情
</router-link>
// 编程式路由跳转
this.$router.push({name:'detail', params:{id: 5, title: '介绍'}})
this.$router.push('/detail/' + id)
如何获取params
参数
// 详情组件(detail)
$route.params.id // 即可获取传递过来的参数
(2)query方式
query方式跳转,路由表无需配置
// 跳转方法 to的字符串写法
<router-link :to="`/detail?id=${id}&title=${title}`">跳转详情页面</router-link>
// to的对象写法
<router-link :to="{path: '/detail', query: {id: id, title: title}}">跳转详情页面</router-link>
// 编程式路由跳转
this.$router.push({path: '/detail', query: {id: id, title: title}})
this.$router.push(`/detail?id=${id}&title=${title}`)
如何获取query
参数
// 详情组件(detail)
$route.query // 可以获取到传递过来的参数