Vue Router 4目前處於測試階段。讓咱們看一下這個新版本中的一些很酷的功能。javascript
Vue 3引入了 createApp
API,它改變了將插件添加到Vue實例的方式。因爲這個緣由,過去版本的Vue Router將不兼容Vue 3。vue
Vue Router 4引入了 createRouter
API,能夠建立一個可與Vue 3一塊兒安裝的路由器實例。java
src/router/index.jsgit
import { createRouter } from "vue-router"; export default createRouter({ routes: [...], });
src/main.jsgithub
import { createApp } from "vue"; import router from "./router"; const app = createApp({}); app.use(router); app.mount("#app");
在以前的Vue Router版本中,你能夠設置 mode
選項設置導航的模式。vue-router
hash
模式利用URL hash來模擬完整的URL,這樣當URL發生變化時,頁面不會被從新加載。history
利用HTML5 History API來實現URL導航,而不須要從新加載頁面。app
src/router/index.js測試
// Vue Router 3 const router = new VueRouter({ mode: "history", routes: [...] });
在Vue Router 4中,這些模式已被抽象到模塊中,能夠將其導入並分配給新的 history
選項。這種額外的靈活性使你能夠根據須要自定義路由歷史記錄的實現。spa
src/router/index.js插件
// Vue Router 4 import { createRouter, createWebHistory } from "vue-router"; export default createRouter({ history: createWebHistory(), routes: [], });
當路由使用新的 .addRoute
方法運行時,Vue Router 4將容許你添加動態路由。
這可能不是你天天都會使用的功能,可是確實有一些有趣的用例。例如,假設你正在爲一個文件系統應用程序建立一個用戶界面,而且但願動態添加路徑,你能夠這樣作:
src/components/FileUploader.vue
methods: { uploadComplete (id) { router.addRoute({ path: `/uploads/${id}`, name: `upload-${id}`, component: FileInfo }); } }
你還可使用如下相關方法:
removeRoute
hasRoute
getRoutes
導航守衛是Vue Router的鉤子,容許用戶在導航事件以前或以後運行自定義邏輯,如 beforeEach
、`beforeRouterEnter
等。
它們一般用於檢查用戶是否有權限訪問某個頁面,驗證動態路由參數,或者銷燬監聽器。
自定義邏輯運行後,next
回調用於確認路由、聲明錯誤或重定向。
在第4版中,你能夠從鉤子中返回一個值或Promise來代替。這將容許像下面這樣方便的速記。
// Vue Router 3 router.beforeEach((to, from, next) => { if (!isAuthenticated) { next(false); } else { next(); } }) // Vue Router 4 router.beforeEach(() => isAuthenticated);
這些只是版本4中新增的一些新功能。您能夠在Vue Router Next倉庫中瞭解更多信息。
感謝Eduardo和團隊爲Vue Router 4所作的巨大努力!
最近整理了一份優質視頻教程資源,想要的能夠關注公衆號便可免費領取哦!