SoFunction
Updated on 2025-04-05

Detailed explanation of vue-router 4 usage examples

Although most of the APIs of vue-router 4 remain unchanged, they exist in plug-ins in vue3, so there are certain changes when used. Next, learn how it is used.

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 the installation is completed, you can view the version of vue-router in the file

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

Create a new router folder, create a new file:

import { createRouter,createWebHashHistory } from "vue-router";

const routes = [
 {
  path:'',
  component:()=>import("../views/login/")
 },
 {
  path:'/home',
  component:()=>import("../views/home/")
 }
]

const router = createRouter({
 history:createWebHashHistory('/'),
 routes
})

export default router

Then introduce router in .

import { createApp } from 'vue'
import App from './'
import router from "./router/index"

const app = createApp(App)
(router)
('#app')

Note: When component introduced the component before, the .vue suffix could be omitted later, 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 adding the route dynamically adds two situations, namely:

// Dynamically add routes--add to root by default({
 path:'/my',
 name:'my',
 component:()=>import("../views/my/")
})

// Dynamically add subroutine route('my',{
 path:'/info',
 component:()=>import("../views/my/")
})

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

2.2. Combining with composition

Get router in the event, perform route jumps and other operations.

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

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

UseRouter to obtain the route before performing operations. You can also operate on the current route. The following are the monitoring cases:

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

<script>
import { useRouter,useRoute } from "vue-router"
import { watch } from "@vue/runtime-core"
export default {
 setup(){
  const route = useRoute()
  // Responsive object when routed, can monitor changes  watch(()=>,query=>{
   ('Latest',query)
  })
 }
}
</script>

3. Navigation Guard

Navigation guards are mainly used to guard navigation through jump or cancellation. There are many ways to implant routing navigation: global, single route-only or component-level.

3.1. Global Guard

((to,from,next)=>{
 ('Global Front Guard');
})
((to,from)=>{
 ('Global Post-Hook');
})

The same as before, without any changes.

3.2. Route exclusive guard

({
 path:'/my',
 name:'my',
 component:()=>import("../views/my/"),
 beforeEnter:(to,from)=>{
  ('Route exclusive guard');
 }
})

3.3. Guards within components

The guards in the component are different from before. In vue-router4, the required plug-ins need to be introduced from vue-router.

<script>
import {  onBeforeRouteLeave } from "vue-router"
export default {
 setup(){
 onnBeforeRouteLeave((to,from)=>{
  const answer = ('Check to leave?')
  if(answer){
   ('Don't leave');
   return false
  }
  })
 }
}
</script>

4. Destructive changes occur in vue-router4

4.1. Instance creation method

// Previous creation methodconst router = new VueRouter({
 
})
new Vue({
 router,
 render:h=>h(App)
}).$mount("#app")

// vue-router4 creation methodimport { createRouter } from "vue-router"
const router = createRouter({

})
createApp(App).use(router).mount("#app")

4.2. Change of mode declaration method

//Beforeconst router = new VueRouter({
 mode:"hash"
})

//Newimport { createRouter, createWebHashHistory } from "vue-router"
const router = createRouter({
 history:createWebHashHistory()
})

The previous mode was replaced with history, and its options were:

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

4.3. The base attribute is merged

The base option is moved to createWebHistory.

//Beforeconst router = new VueRouter({
 base:"/"
})

//Newimport { createRouter, createWebHashHistory } from "vue-router"
const router = createRouter({
 history:createWebHashHistory('/')
})

4.4. Wildcard * is cancelled

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

//vue-router 4
{
 path:'/:pathMatch(.*)*',
 component:()=>import("../components/")
}
//is a regular expression

4.5. isReady() replaces onReady

//Before(onSuccess,onError)//Success and failure callback
//vue-router 4
().then(()=>{
 //success}).catch(err=>{
 //fail})

4.6. scrollBehavior changes

const router = createRouter({
 scrollBehavior(to, from, savedPosition) {
  // Always scroll to top  return { top: 0, left:0 }
 },
})
//Previously used{ x:0, y:0 } Replaced with { top: 0, left:0 }

4.7. Keep-alive and transition must be used inside the 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 removes some attributes

Remove append attribute

//Before<router-link to="child" append >Jump<router-link>

//vue-router 4
<router-link :to="append( $ , 'child' )" append >Jump<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 removed

4.9. The parent property of route is removed

4.10. The pathToRegexpOptions option is removed and other contents are replaced.

4.11. Routes option is required

4.12. Jumping non-existent naming route error

I jumped to a route that did not exist before. The page was empty and the root path would be redirected. This is unreasonable, so vue3 reported an error.

4.13. An exception will be thrown if the required parameters are missing.

4.14. If the path of the named subroutine is empty, no more appends /

The previously generated url will automatically append a / , such as: "/dash/". Side effects: Side effects on subroutines that have set the redirect option.

Here is the article about vue-router 4 Are you really proficient? That’s all for the article. For more related vue-router 4 content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!