Although most of the APIs of vue-router 4 remain unchanged, it exists as a plugin in vue3, so there are some changes in its use. Next, let’s learn how to use it. 1. Install and create an instanceInstall the latest version of vue-router npm install vue-router@4 or yarn add vue-router@4 After the installation is complete, you can view the version of vue-router in the package.json file "dependencies": { "vue": "^3.2.16", "vue-router": "4" }, Create a new router folder and a new index.js file: 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 Then import the router in main.js. import { createApp } from 'vue' import App from './App.vue' import router from "./router/index" const app = createApp(App) app.use(router) app.mount('#app') Note: Previously, when you imported a component into a component, you could omit the .vue suffix, but in vue-router 4, you cannot omit the suffix, otherwise you will get an error. 2. New features of vue-router42.1 Dynamic RoutingWhen addRoute dynamically adds routes, there are two situations: //Dynamically add routes--by default, add to the root router.addRoute({ path:'/my', name:'my', component:()=>import("../views/my/index.vue") }) //Dynamically add sub-routes router.addRoute('my',{ path:'/info', component:()=>import("../views/my/info.vue") }) When adding a child route, the first attribute value is the name attribute value of the parent route. 2.2, Combination with compositionGet the router in the event and perform operations such as route jump. <template> <button @click="backToHome">Go to home page</button> </template> <script> import { useRouter } from "vue-router" export default { setup(){ const router = useRouter() return { backToHome(){ router.push("/") }, } } } </script> Get the route through useRouter before operating. You can also operate on the current route. The following is an example of listening to route.query: <template> <div>Monitor route changes</div> </template> <script> import { useRouter,useRoute } from "vue-router" import { watch } from "@vue/runtime-core" export default { setup(){ const route = useRoute() //route is a responsive object that can monitor changes watch(()=>route.query,query=>{ console.log('latest',query) }) } } </script> 3. Navigation GuardNavigation guards are mainly used to guard navigation by redirecting or canceling. There are many ways to embed navigation into routing: globally, for a single route, or at the component level. 3.1 Global Guardrouter.beforeEach((to,from,next)=>{ console.log('global front guard'); }) router.afterEach((to,from)=>{ console.log('global post-hook'); }) Same as before, no changes. 3.2. Exclusive router guardrouter.addRoute({ path:'/my', name:'my', component:()=>import("../views/my/index.vue"), beforeEnter:(to,from)=>{ console.log('Route exclusive guard'); } }) 3.3. Guards within componentsThe guards in the component are different from those used before. In vue-router4, you need to import the required plug-ins from vue-router. <script> import { onBeforeRouteLeave } from "vue-router" export default { setup(){ onnBeforeRouteLeave((to,from)=>{ const answer = window.confirm('Are you sure you want to leave?') if(answer){ console.log('do not leave'); return false } }) } } </script> 4. Destructive changes in vue-router44.1. Instance creation method//Previous creation method const router = new VueRouter({ }) new Vue({ router, render:h=>h(App) }).$mount("#app") //vue-router4 creation method import { createRouter } from "vue-router" const router = createRouter({ }) createApp(App).use(router).mount("#app") 4.2. Changes in mode declaration//Before const router = new VueRouter({ mode:"hash" }) //New import { createRouter, createWebHashHistory } from "vue-router" const router = createRouter({ history:createWebHashHistory() }) The previous mode is replaced by history, and its options are changed as follows:
4.3. base attributes are mergedThe base option was moved to createWebHistory. //Before const router = new VueRouter({ base:"/" }) //New import { createRouter, createWebHashHistory } from "vue-router" const router = createRouter({ history:createWebHashHistory('/') }) 4.4. Wildcard * is cancelled//Before{ path:'*', component:()=>import("../components/NotFound.vue") } //vue-router 4 { path:'/:pathMatch(.*)*', component:()=>import("../components/NotFound.vue") } // is a regular expression 4.5. isReady() instead of onReady//Before router.onReady(onSuccess, onError) //Success and failure callbacks //vue-router 4 router.isReady().then(()=>{ //Success}).catch(err=>{ //fail}) 4.6. scrollBehavior changesconst router = createRouter({ scrollBehavior(to, from, savedPosition) { // Always scroll to the top return { top: 0, left:0 } }, }) //The previous { x:0, y:0 } is replaced with { top: 0, left:0 } 4.7. keep-alive and transition must be used inside router-view//Before <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 removed some attributesRemove the append attribute //Before <router-link to="child" append > jump to <router-link> //vue-router 4 <router-link :to="append( $route.path , 'child' )" append > jump to <router-link> tag removed //Before <router-link to="/" tag="span">Jump</router-link> //vue-router 4 <router-link to="/" custom> <span>Jump</span> </router-link> event is removed 4.9. The parent attribute of route is removed4.10. pathToRegexpOptions option is removed and replaced by other content4.11. The routes option is required4.12. Error reporting when redirecting to a non-existent named routePreviously, when jumping to a non-existent route, the page was empty and the root path would be redirected, which was unreasonable, so Vue3 reported an error. 4.13. Missing required parameters will throw an exception4.14. If the path of a named subroute is empty, no / is appendedThe previously generated URL will automatically have a / appended to it, such as "/dash/". Side effects: Has side effects on child routes that have the redirect option set. Are you really proficient in this article about vue-router 4? This is the end of the article. For more relevant vue-router 4 content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Website performance: Image and Cookie optimization and mobile application optimization
>>: Let the web page redirect to other pages after opening for a few seconds
Detailed explanation of creating MySql scheduled ...
Table of contents When developing, analyzing the ...
In MySQL, you can specify multiple indexes for a ...
Table of contents 1. Realistic Background 2. Agre...
I won't say much nonsense, let's just loo...
Table of contents Zabbix custom monitoring nginx ...
1. Business scenario introduction Suppose there i...
Mysql5.7.19 version is a new version launched thi...
Table of contents Actual combat process Let's...
1. After connecting and logging in to MySQL, firs...
I recently watched Apple's press conference a...
Request logic Front-end --> Request nginx via ...
Implemented according to the online tutorial. zab...
Table of contents 01-Event Bubbling 1.1- Introduc...
The WeChat mini-program native components camera,...