#基础
入门
html
<div>
<router-link to='/'>首页</router-link>
<router-view />
</div>
- 使用router-link 组件进行导航
- 通过to来指定链接
- 标签 href可以正确使用。
- vue-router 可以在不重新加载页面的情况下更改url,处理url的生成。
- router-view 路由出口,匹配到组件渲染到这里。
- router-view 与url对应的内容显示,适应布局。
javascript
const Home = {template:'<div>Home</div>'}
const About = {template:'<div>About</div>'}
const routes =[
{path:'/',component:Home},
{path:'/about',component:About}
]
const router = VueRouter.createRouter({
history:VueRouter.createWebHashHistory(),
routers
})
const app = Vue.createApp({})
app.use(router)
app.mout('#app')
如何使用?
computed:{
username(){
this.$route.params.username
}
}
goToDashBoard(){
if(isAuthenticated){
this.$router.push('/dashboard')
}else{
this.$router.push('login')
}
}
- 在set up中 使用 useRouter 和 useRoute ,
- this.$router === router
带参数的动态路由
const routes = [
{ path:'users/:id' , component :User }
]
- 现在像/users/johnny和 /users/jolyne 映射到同一个路由中
- 路径参数由params 值以this.$route.params 展示出来
$route.params.id
匹配模式 | 匹配路径 | $route.params |
---|---|---|
/users/:username | /users/eduardo | {username:‘eduardo’ |
/users/:username/posts/:postid | /user/eduardo/posts/123 | {username:‘eduardo’,posiId:123} |
除了 r o u t e . p a r a m s . 外还有 route.params.外还有 route.params.外还有route.query(url中存在的参数)
相应路由参数的变化
相同的组件实例被重复使用,意味着组件生命周期钩子不会被调用。
const User = {
created(){
this.$watch(
()=>this.$route.params,
(toParams,oerviousParams)=>[
// 对路由变化做出相应
}
)
}
}
或
const User = {
async beforeRouteUpdate(to,from){
this.userData = await FetchUser(to.prams.id)
}
}
捕获所有路由或404 Not found
匹配任意路由,可以选择正则表达式,如
const routes = [
{path:'/:pathMatch(.*)*,name:'NotFound',component:'NotFount'},
{path:'/user-:afterUser(.*)',component:'UserGeneric}
]
- 将匹配所有内容将其放在$route.params.pathMatch下,
- 将匹配以’/user-'开头的所有内容,并将其放在‘$route.params.afterUser下
- 自定义正则表达式,pathMatch 标记为可选可选可重复,目的:需要时候,path可以拆分为数组。
router.push({
name:'NotFound',
params:{pathMatch:this.route.path.substring(1).split('/')},
query:this.$router.query,
hash:this.$router.hash
})
路由的匹配语法
在参数中自定义正则
const routes = [
{path:'/o/:orderId'}, //匹配/o/3549
{path:'/p/:productName'}.//匹配/o/books
]
偶尔还可以这样写
const routes = [
{path:'/:orderId(\\d+)'} // 仅匹配数字
{path:'/:productName'} //匹配任何内容
]
可重复的参数
如果你需要匹配具有多个部分路由组成。
const routes = [
//匹配 :chapters -> 匹配/one,/one/tow,/one/tow/three
{path:'/:chapters+'}
]
为你提供了一个传递时候的字符串
// 给定 { path: '/:chapters*', name: 'chapters' },
router.resolve({ name: 'chapters', params: { chapters: [] } }).href
// 产生 /
router.resolve({ name: 'chapters', params: { chapters: ['a', 'b'] } }).href
// 产生 /a/b
// 给定 { path: '/:chapters+', name: 'chapters' },
router.resolve({ name: 'chapters', params: { chapters: [] } }).href
// 抛出错误,因为 `chapters` 为空
? router.resolve({name:‘chapters’,params:{chapters:[]} }).href 为空报错么?
sensitive 与 strict 路由配置
路由不区分大小写,匹配/users /users /users /Users
可以通过strict来控制或sensitive