路由
vue-router4保持了大部分API不变,我们只关注变化部分即可。
快速开始
引入
cdn
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/4.0.6/vue-router.cjs.js"></script>
npm
npm install vue-router@next
对比变化
-
实例创建方式
-
history选项替代了mode选项
* history:createWebHistory()
* hash:createWebHashHistory()
* abstract:createMemoryHistory() -
base选项移动至createWebHistory等方法中
-
通配符* 被移除
-
isReady()替代onReady()
//before
router.push()
//now
router.isReady().then(onSuccess).catch(onError)
- scrollBehavior变化
x,y变成top,left - 现在keep-alive和transition必须用在router-view内部
//before
<keep-alive>
<router-view></router-view>
</keep-alive>
//now
<router-view v-solt="{Component}">
<keep-alive>
<component :is="Component">
</keep-alive>
</router-view>
- router-link移除了一票属性
- append
<router-link to="child-route" append>
<router-link :to="append($route.path,'child-route')">
app.config.globalProperties.append=(path,pathToAppend)=>{
return path + pathToAppend
}
- tag/event
<router-link to="/xx" tag="span" event="dbclick"></router-link>
<router-link to="/xx" custom v-solt="{navigate}">
<span @dbclick="navigate">xxx</span>
</router-link>
- exact:现在完全匹配逻辑简化了
- mixins中的路由守卫将被忽略
- match方法被移除,使用resolve替代
- 移除router.getMathedComponents()
router.currentRoute.value.matched
- 包括首屏导航在内所有导航均为异步
app.use(router)
router.isReady().then(()=>app.mount('#app'))
如果首屏存在路由守卫,则可以不等待就绪直接挂载,产生结果将和vue2相同
- route的parent属性被移除
const partent=this.$route.matched[this.$route.matched.length-2]
- pathToRegexpOptions选项被移除
- pathToRegexpOptions=>strict
- ccaseSensitive=>sensitive
createRouter({
strict:boolean,
sensitive:boolean
})
- 使用history.state
//之前
history.pushState(myState,'',url)
//现在
router.push(url)
history.replaceState({...history.state,...myState},'')
//之前
history.replaceState({},'',url)
//现在
history.replaceState(history.state,'',url)
- routes选项是必填项
createRouter({routes:[]})
17.跳转不存在命名路由报错
router.push({name:'dashboad'})
18.缺少必填参数会抛出异常
19.命名子路由如果path为空的时候不再追加/
[
path:'/dashboard',
children:[
{path:'',component:DashboardDefault}
]
]
以前生成url:/dashboard/
副作用:给设置了重定向redirect选项的子路由带来副作用
[
path:'/dashboard',
children:[
{path:'',redirect:'home'},
{path:'home',component:Home},
]
]
/dashboard/home
/home
- $route属性编码行为
parms/query/hash
- Path/fullpath不再做解码
- hash会被解码
- push、resolve和replace,字符串参数,或者对象参数path属性必须编码
- query中+不处理,stringifyQuery