Detailed explanation of vue-router 4 usage examples

Detailed explanation of vue-router 4 usage examples

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 instance

Install 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-router4

2.1 Dynamic Routing

When 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 composition

Get 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 Guard

Navigation 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 Guard

router.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 guard

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

3.3. Guards within components

The 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-router4

4.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:

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

4.3. base attributes are merged

The 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 changes

const 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 attributes

Remove 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 removed

4.10. pathToRegexpOptions option is removed and replaced by other content

4.11. The routes option is required

4.12. Error reporting when redirecting to a non-existent named route

Previously, 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 exception

4.14. If the path of a named subroute is empty, no / is appended

The 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:
  • Detailed explanation of the use of router-view components in Vue
  • A simple example of using Vue3 routing VueRouter4
  • Detailed explanation of the installation and use of Vue-Router
  • Complete steps to use vue-router in vue3
  • How to use Vue-router routing
  • Do you know how to use Router in vue3.0?

<<:  Website performance: Image and Cookie optimization and mobile application optimization

>>:  Let the web page redirect to other pages after opening for a few seconds

Recommend

Detailed explanation of how to create MySql scheduled tasks in navicat

Detailed explanation of creating MySql scheduled ...

Native js to implement form validation function

Table of contents When developing, analyzing the ...

Reasons and solutions for MySQL selecting the wrong index

In MySQL, you can specify multiple indexes for a ...

MySQL8.0.18 configuration of multiple masters and one slave

Table of contents 1. Realistic Background 2. Agre...

mySql SQL query operation on statistical quantity

I won't say much nonsense, let's just loo...

zabbix custom monitoring nginx status implementation process

Table of contents Zabbix custom monitoring nginx ...

MySQL sharding details

1. Business scenario introduction Suppose there i...

Docker starts MySQL configuration implementation process

Table of contents Actual combat process Let's...

A simple method to regularly delete expired data records in MySQL

1. After connecting and logging in to MySQL, firs...

How to implement email alert in zabbix

Implemented according to the online tutorial. zab...

A brief analysis of event bubbling and event capture in js

Table of contents 01-Event Bubbling 1.1- Introduc...