Detailed Explanation of vue router 4 Using Examples

  • 2021-12-04 17:56:06
  • OfStack

Directory 1. Install and create instances 2. vue-router4 New Feature 2.1, Dynamic Routing 2.2, Combination with composition 3. Navigation Guard 3.1, Global Guard 3.2, Routing Exclusive Guard 3.3, Within Component Guard 4. vue-router4 Destructive Change 4.1, Instance Creation Mode 4.2, Schema Declaration Mode Change 4.3, base Attribute Merge 4.4, Wildcard Character * Cancel 4.5, isReady () Replace onReady 4.6, scrollBehavior Change 4.7, keep-alive and transition Must Be Used Within router-view 4.8, router-link Remove 1 Part 4.11, routes option required 4.13. Missing required parameter throws exception

Although vue-router 4 most API remains the same, it exists as a plug-in in vue3, so there is a definite change in use. Next, learn how to use it.

1. Install and create an instance

Install the latest version of vue-router


npm install vue-router@4 

 Or 

yarn add vue-router@4

After installation, you can view the version of vue-router in the package. json file


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},

New router folder, 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 router is introduced 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: When component introduced the component before, the suffix. vue can be omitted, but in vue-router 4, the suffix cannot be omitted, otherwise an error will be reported.

2. New features of vue-router4

2.1. Dynamic Routing

When addRoute dynamically adds routes, there are two situations:


// Add routes dynamically -- Add to root by default 
router.addRoute({
 path:'/my',
 name:'my',
 component:()=>import("../views/my/index.vue")
})

// Dynamic addition of child routes 
router.addRoute('my',{
 path:'/info',
 component:()=>import("../views/my/info.vue")
})

When a child route is added, the first attribute value is the name attribute value of the parent route.

2.2. Combination with composition

Get router in the event and perform routing jump and other operations.


<template>
  <button @click="backToHome"> Jump to Home Page </button>
</template>

<script>
import { useRouter } from "vue-router"
export default {
 setup(){
  const router = useRouter()
  return{
   backToHome(){
    router.push("/")
   },
  }
 }
}
</script>

The route is obtained through useRouter before operation. You can also operate on the current route route. The following is a case of listening to route. query:


<template>
  <div> Listen for routing changes </div>
</template>

<script>
import { useRouter,useRoute } from "vue-router"
import { watch } from "@vue/runtime-core"
export default {
 setup(){
  const route = useRoute()
  //route Time-responsive objects that can monitor changes 
  watch(()=>route.query,query=>{
   console.log(' Latest ',query)
  })
 }
}
</script>

3. Navigation Guard

Navigation guards are mainly used to guard navigation by jumping or canceling, and there are many ways to embed in route navigation: global, exclusive to a single route or component level.

3.1. Global Guard


router.beforeEach((to,from,next)=>{
 console.log(' Global front guard ');
})
router.afterEach((to,from)=>{
 console.log(' Global post hook ');
})

It is the same as the previous use, without any change.

3.2. Route Exclusive Guard


router.addRoute({
 path:'/my',
 name:'my',
 component:()=>import("../views/my/index.vue"),
 beforeEnter:(to,from)=>{
  console.log(' Routing exclusive guard ');
 }
})

3.3. Guards in components

The guard in the component is different from the previous use. In vue-router4, the required plug-in needs to be introduced from vue-router.


<script>
import {  onBeforeRouteLeave } from "vue-router"
export default {
 setup(){
 onnBeforeRouteLeave((to,from)=>{
  const answer = window.confirm(' Do you confirm your departure ')
  if(answer){
   console.log(' Don't leave ');
   return false
  }
  })
 }
}
</script>

4. Destructive changes in vue-router4

4.1. Instance Creation Method


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
0

4.2. Change the mode of schema declaration


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
1

The previous mode has been replaced by history, and its options have changed as follows:

history - > createWebHistory hash - > createWebHashHistory abstract - > createMemoryHistory

4.3. The base attributes are merged

The base option is moved to createWebHistory.


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
2

4.4. Wildcard * is canceled


// Before 
{
 path:'*',
 component:()=>import("../components/NotFound.vue")
}

//vue-router 4
{
 path:'/:pathMatch(.*)*',
 component:()=>import("../components/NotFound.vue")
}
// Yes 1 Regular expressions 

4.5, isReady () Replaces onReady


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
4

4.6. scrollBehavior changes


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
5

4.7. keep-alive and transition must be used inside router-view


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
6

4.8. router-link Remove 1 Partial Attribute

Remove append property


"dependencies": {
 "vue": "^3.2.16",
 "vue-router": "4"
},
7

tag removed


// Before 
<router-link to="/" tag="span"> Jump </router-link>

//vue-router 4
<router-link to="/" custom>
 <span> Jump </span>  
</router-link>

event removed

4.9. The parent attribute of route is removed

4.10. The pathToRegexpOptions option is removed and other content is replaced

4.11, routes option required

4.12. Jump Named Routes without Existence to Report Errors

Before jumping to a non-existent route, the page is empty and the root path will be redirected, which is unreasonable, so vue3 reported an error.

4.13. Missing required parameter throws exception

4.14. Named sub-route If path is empty, no append/

A/is automatically appended to the previously generated url, such as "/dash/". Side effects: Side effects on child routes with redirect option set.


Related articles: