路由
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)
//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 to="child-route" append>
<router-link :to="append($route.path,'child-route')">
app.config.globalProperties.append=(path,pathToAppend)=>{
return path + pathToAppend
}
<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>
router.currentRoute.value.matched
app.use(router)
router.isReady().then(()=>app.mount('#app'))
如果首屏存在路由守卫,则可以不等待就绪直接挂载,产生结果将和vue2相同
const partent=this.$route.matched[this.$route.matched.length-2]
createRouter({
strict:boolean,
sensitive:boolean
})
//之前
history.pushState(myState,'',url)
//现在
router.push(url)
history.replaceState({...history.state,...myState},'')
//之前
history.replaceState({},'',url)
//现在
history.replaceState(history.state,'',url)
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