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 Deepin using docker to install mysql database

Query the MySQL source first docker search mysql ...

Simple analysis of EffectList in React

Table of contents EffectList Collection EffectLis...

In-depth understanding of MySQL long transactions

Preface: This article mainly introduces the conte...

VUE implements a Flappy Bird game sample code

Flappy Bird is a very simple little game that eve...

Summary of block-level elements, inline elements, and variable elements

Block element p - paragraph pre - format text tabl...

Detailed explanation of how to view the current number of MySQL connections

1. View the detailed information of all current c...

JavaScript web form function communication full of practical information

1. Introduction Earlier we talked about the front...

In-depth understanding of asynchronous waiting in Javascript

In this article, we’ll explore how async/await is...

How to use vue-bootstrap-datetimepicker date plugin in vue-cli 3

Demand Background Recently, I plan to use Vue and...

Detailed explanation of Docker Volume permission management

Volume data volume is an important concept of Doc...

Analysis of the principle and usage of MySQL continuous aggregation

This article uses examples to illustrate the prin...

Layui implements sample code for multi-condition query

I recently made a file system and found that ther...