vue-router 4使用實(shí)例詳解
雖然 vue-router 4 大多數(shù) API 保持不變,但是在 vue3 中以插件形式存在,所以在使用時(shí)有一定的變化。接下來就學(xué)習(xí)學(xué)習(xí)它是如何使用的。
一、安裝并創(chuàng)建實(shí)例
安裝最新版本的 vue-router
npm install vue-router@4 或 yarn add vue-router@4
安裝完成之后,可以在 package.json 文件查看vue-router的版本
"dependencies": { "vue": "^3.2.16", "vue-router": "4" },
新建 router 文件夾,新建 index.js文件:
import { createRouter,createWebHashHistory } from "vue-router"; const routes = [ { path:'', component:()=>import("../views/login/index.vue") }, { path:'/home', component:()=>import("../views/home/index.vue") } ] const router = createRouter({ history:createWebHashHistory('/'), routes }) export default router
然后在main.js 中引入 router 。
import { createApp } from 'vue' import App from './App.vue' import router from "./router/index" const app = createApp(App) app.use(router) app.mount('#app')
注意:之前 component 引入組件的時(shí)候,后邊可以省略 .vue 后綴,但在 vue-router 4這不能省略后綴,否則就報(bào)錯(cuò)了。
二、vue-router4 新特性
2.1、動(dòng)態(tài)路由
addRoute 動(dòng)態(tài)添加路由時(shí),有兩種情況,分別為:
//動(dòng)態(tài)添加路由--默認(rèn)添加到根 router.addRoute({ path:'/my', name:'my', component:()=>import("../views/my/index.vue") }) //動(dòng)態(tài)添加子路由 router.addRoute('my',{ path:'/info', component:()=>import("../views/my/info.vue") })
添加子路由時(shí),第一個(gè)屬性值是父級路由的 name 屬性值。
2.2、與 composition 組合
在 事件中獲取 router ,進(jìn)行路由跳轉(zhuǎn)等操作。
<template> <button @click="backToHome">跳轉(zhuǎn)到首頁</button> </template> <script> import { useRouter } from "vue-router" export default { setup(){ const router = useRouter() return{ backToHome(){ router.push("/") }, } } } </script>
通過 useRouter 獲取到路由之后再進(jìn)行操作。也可以對當(dāng)前路由route進(jìn)行操作。以下是監(jiān)聽route.query的案例:
<template> <div>監(jiān)聽路由變化</div> </template> <script> import { useRouter,useRoute } from "vue-router" import { watch } from "@vue/runtime-core" export default { setup(){ const route = useRoute() //route時(shí)響應(yīng)式對象,可監(jiān)控變化 watch(()=>route.query,query=>{ console.log('最新的',query) }) } } </script>
三、導(dǎo)航守衛(wèi)
導(dǎo)航守衛(wèi)主要用來通過跳轉(zhuǎn)或取消的方式守衛(wèi)導(dǎo)航,有很多種方式植入路由導(dǎo)航中:全局的、單個(gè)路由獨(dú)享的或者組件級的。
3.1、全局守衛(wèi)
router.beforeEach((to,from,next)=>{ console.log('全局前置守衛(wèi)'); }) router.afterEach((to,from)=>{ console.log('全局后置鉤子'); })
與之前的使用都一樣,沒有任何變化。
3.2、路由獨(dú)享守衛(wèi)
router.addRoute({ path:'/my', name:'my', component:()=>import("../views/my/index.vue"), beforeEnter:(to,from)=>{ console.log('路由獨(dú)享守衛(wèi)'); } })
3.3、組件內(nèi)的守衛(wèi)
組件內(nèi)的守衛(wèi)與之前使用不同,vue-router4中,需要從vue-router內(nèi)引入需要的插件。
<script> import { onBeforeRouteLeave } from "vue-router" export default { setup(){ onnBeforeRouteLeave((to,from)=>{ const answer = window.confirm('是否確認(rèn)離開') if(answer){ console.log('不離開'); return false } }) } } </script>
四、vue-router4 發(fā)生破壞性變化
4.1、實(shí)例創(chuàng)建方式
//以前創(chuàng)建方式 const router = new VueRouter({ }) new Vue({ router, render:h=>h(App) }).$mount("#app") //vue-router4創(chuàng)建方式 import { createRouter } from "vue-router" const router = createRouter({ }) createApp(App).use(router).mount("#app")
4.2、模式聲明方式改變
//之前 const router = new VueRouter({ mode:"hash" }) //新的 import { createRouter, createWebHashHistory } from "vue-router" const router = createRouter({ history:createWebHashHistory() })
之前的mode替換成了 history ,它的選項(xiàng)變化分別為:
- history -> createWebHistory
- hash -> createWebHashHistory
- abstract -> createMemoryHistory
4.3、base屬性被合并
base 選項(xiàng)被移至 createWebHistory 中。
//之前 const router = new VueRouter({ base:"/" }) //新的 import { createRouter, createWebHashHistory } from "vue-router" const router = createRouter({ history:createWebHashHistory('/') })
4.4、通配符 * 被取消
//之前 { path:'*', component:()=>import("../components/NotFound.vue") } //vue-router 4 { path:'/:pathMatch(.*)*', component:()=>import("../components/NotFound.vue") } //是一個(gè)正則表達(dá)式
4.5、isReady() 替代 onReady
//之前 router.onReady(onSuccess,onError)//成功和失敗回調(diào) //vue-router 4 router.isReady().then(()=>{ //成功 }).catch(err=>{ //失敗 })
4.6、scrollBehavior 變化
const router = createRouter({ scrollBehavior(to, from, savedPosition) { // 始終滾動(dòng)到頂部 return { top: 0, left:0 } }, }) //之前使用的{ x:0, y:0 } 替換成了 { top: 0, left:0 }
4.7、keep-alive 和 transition 必須用在 router-view 內(nèi)部
//之前 <keep-alive> <router-view /> </keep-alive> //vue-router 4 <router-view v-slot="{component}"> <keep-alive> <component :is="component" /> </keep-alive> </router-view>
4.8、router-link 移除了一部分屬性
移除 append 屬性
//之前 <router-link to="child" append >跳轉(zhuǎn)<router-link> //vue-router 4 <router-link :to="append( $route.path , 'child' )" append >跳轉(zhuǎn)<router-link>
tag 被移除
//之前 <router-link to="/" tag="span">跳轉(zhuǎn)</router-link> //vue-router 4 <router-link to="/" custom> <span>跳轉(zhuǎn)</span> </router-link>
event 被移除
4.9、route 的 parent 屬性被移除
4.10、pathToRegexpOptions選項(xiàng)被移除,其他內(nèi)容替換
4.11、routes選項(xiàng)是必填項(xiàng)
4.12、跳轉(zhuǎn)不存在的命名路由報(bào)錯(cuò)
之前跳轉(zhuǎn)到不存在的路由,頁面是空的,會(huì)重定向根路徑,這是不合理的,所以vue3報(bào)錯(cuò)了。
4.13、缺少必填參數(shù)會(huì)拋出異常
4.14、命名子路由如果 path 為空的時(shí)候,不再追加 /
之前生成的 url 會(huì)自動(dòng)追加一個(gè) / ,如:"/dash/"。副作用:給設(shè)置了 redirect 選項(xiàng)的子路由帶來副作用。
到此這篇關(guān)于vue-router 4 你真的熟練嗎?的文章就介紹到這了,更多相關(guān)vue-router 4內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue 跳轉(zhuǎn)到其他頁面并關(guān)閉當(dāng)前頁面的實(shí)現(xiàn)代碼
我在做一個(gè)調(diào)用虛擬機(jī)錄屏的一個(gè)操作,需要在瀏覽器頁面上,點(diǎn)擊按鈕后,關(guān)閉當(dāng)前頁面里的某一個(gè)頁面,并且打開瀏覽器新頁面是虛擬機(jī)的頁面,本文給大家介紹vue 跳轉(zhuǎn)到其他頁面并關(guān)閉當(dāng)前頁面的實(shí)現(xiàn)代碼,感興趣的朋友一起看看吧2023-09-09vue的ElementUI form表單如何給label屬性字符串中添加空白占位符
這篇文章主要介紹了vue的ElementUI form表單如何給label屬性字符串中添加空白占位符問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10Vite打包優(yōu)化之縮小打包體積實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了使用Vite縮小打包體積如何實(shí)現(xiàn)的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01vue再次進(jìn)入頁面不會(huì)再次調(diào)用接口請求問題
這篇文章主要介紹了vue再次進(jìn)入頁面不會(huì)再次調(diào)用接口請求問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08基于Vue實(shí)現(xiàn)卡片無限滾動(dòng)動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了如何利用Vue制作出卡片無限滾動(dòng)動(dòng)畫,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)有一定幫助,需要的可以參考一下2022-05-05vue?+?ele?實(shí)現(xiàn)下拉選擇框和下拉多選選擇框處理方案
這篇文章主要介紹了vue?+?ele?實(shí)現(xiàn)下拉選擇框和下拉多選選擇框處理方案,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08