[Vue3] Vue-Router routing and routing navigation guard

Front-end and back-end separation stage routing

  • With the emergence of Ajax, there is a development model with front-end and back-end separation
  • The backend provides API to return data, the frontend obtains data through Ajax, and renders it to the page through js
  • advantage. Clear front-end and back-end responsibilities

Single page rich application stage

  • The biggest feature of SPA is to add a layer of front-end routing on the basis of the separation of front-end and back-end
  • That is, the front end maintains a set of routing rules
  • Core, while changing the URL, the page does not refresh as a whole
How does front-end routing achieve URL and content mapping?
  • Listen for URL changes
hash of url
  • The hash of URl is the anchor point (#), which essentially changes the window.location and href attributes
  • We can change and href by directly assigning location.hash (but the page does not refresh)
History of URLs
  • Added in HTML5, there are 6 modes to change the URL without refreshing the page
  • replaceState, replace the original path
  • pushState, using the new path
  • popState, fallback for path
  • go, change path forward or backward
  • forward, change the path forward
  • back, change the path backwards

Basic use of Vue-Router

  • Building a Single Page Application (SPA) with Vue-Router
  • 1. Create a routing object
  • 2. Establish a mapping relationship
  • 3. Let the routing object take effect
  • 4. Mount the router
  • 5, router-view occupying place
  • 6, router-link routing switching
1. Install Vue-Router
npm install vue-router
2. Create index.js under the router file of the new page, route, import page, import route, create routing relationship
  • createWebHashHistory: refers to routing with hash mode, such as /#/order/detail with # path
  • createWebHistory: Routing based on html5 native history API
  • createMemoryHistory: implicitly manage routing based on memory information, suitable for SSR scenarios
import {
    
     createRouter,createWebHashHistory  } from 'vue-router'
//导入
import Home from "../Views/home.vue"
import About from "../Views/about.vue"
//创建路由对象,//建立映射关系
const router = createRouter({
    
    
    history:createWebHashHistory (),//用于指定采用的模式。目前式哈希模式
    routes: [
    	//一般开发里面都会写一个重定向的路径
       {
    
    
            path: '/', redirect: "/home"
        },
        {
    
    
            path: '/home', component: Home
        },
        {
    
    
            path: '/about', component: About
        }
    ]
})

//导出
export default router
3,main.js
import {
    
     createApp } from 'vue'
import App from './App.vue'

//再次导入,告诉app,注意这里的使用方式
import router from './router/index'
createApp(App).use(router).mount('#app')
3. Inside app.vue
<template>
  <p>标题</p>
  <router-view></router-view>
  <div class="nev">
    <router-link to="Home">Home</router-link>
    <router-link to="about">about</router-link>
  </div>
</template>
<script setup>
</script>

<style>
#app {
    
    
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

router-link attribute

  • 1. The replace attribute, the replacement attribute, will not exist in the history
<router-link to="Home" replace>Home</router-link>
  • 2. The to attribute can be a string or an object
<router-link to="Home" replace>Home</router-link>
<router-link :to="{path:'/about'}">about</router-link>
  • 3. active-class attribute
  • Set the class applied after activating the a element, the default is router-link-active
.router-link-active{
    
    
  color :blue;
}
  • 4, exact-active-class attribute
  • The class used for rendering when the link is precisely activated, the default is router-link-exact-active

Routing lazy loading subpackage processing

  • Can improve the rendering efficiency of the first screen
//如果想要分包
const Home=()=>import("../Views/hone.vue")
const About=()=>import("../Views/about.vue")

insert image description here

Other properties of routes

  • name attribute, the unique name of the routing record, you can specify the name to jump when the page jumps
  • Meta attribute, put custom attributes
    insert image description here

Dynamic Routing and Routing Nesting

1. Basic matching of dynamic routing
  • For example: there is a component page, the user needs to pass the user id to enter, but the id is different
  • Therefore: in vue router, you can use a dynamic field in the path to achieve it, called the path parameter
  • /:parameter
    insert image description here
2. If you want to get the passed parameters in the vue page
  • Take it in the template
<template>
  <div><p>about的参数{
    
    {
    
    $route.params.id}}</p></div>
</template>

insert image description here

  • Get it in Vue2's api
 this.$route.params.id
  • Get it in Vue3's api
  • But there are disadvantages, switching printing back and forth is only performed once
<script setup>
  import {
    
    useRoute} from "vue-router"
  //获取router跳转的id
  const route = useRoute()
  console.log(route.params.id)
</script>

insert image description here

  • Solution: I want to monitor the routing router changes in vue3
  • Adds a navigation guard that fires when the current position is about to be updated.
<script setup>
  import {
    
    onBeforeRouteUpdate} from "vue-router"
  //获取router跳转的id
  onBeforeRouteUpdate((to,from)=>{
    
    
    console.log(to,from)
    console.log("form",from.params.id)
    console.log("to",to.params.id)
  })
</script>

Not Foned

  • If you want users to be unable to match the page, the following components will be displayed automatically
    insert image description here
    insert image description here
    insert image description here

  • If you want to parse the path, add a * after it to parse it into an array
    insert image description here
    insert image description here

Nested use of routes

  • Note that nested paths starting with / will be treated as root paths. This allows you to take advantage of component nesting without having to use nested URLs.
  • 1. Add the children[] attribute in the first layer of routing
 {
    
    
            name: "home",
            path: '/home',
            component: Home,
            children: [
                {
    
    
                    path: '/about',
                    component: About
                }
            ]
        },
  • 2, add in the home component
 <router-view></router-view>
  • 3, route jump

Programmatic Navigation for Routing

Navigation, router.push method

insert image description here

Receive query data

insert image description here

router.replace() method, replace the current page
router.back(n) method, return to the previous page, or n pages
The router.forward(n) method takes one step forward, or n steps
router.go(n), page forward or backward, n is positive or negative
history.back(), backtracking history is equivalent to router.go(-1)
history.forward(), forward in history is equivalent to router.go(1)

Dynamically manage routing objects

Dynamically add routes
  • scenes to be used
  • For example, according to different user permissions, register different routes
  • At this time, you can use a method addRoute
  • Similar to the following, if you have permission, add a route
let isAdmin = true
if(isAdmin){
    
    
    router.addRoute({
    
    
        path:"/Admin",
        component:Admin
    })
}
Dynamically add child routes
  • router.addRoute(parentName, route)
  • Where parentName is the name field defined by the parent route.
  • Note: Do not add "/" in front of the sub-routing path
  • Also note that there must be a placeholder router-view in the parent route
let isAdmin = true
if(isAdmin){
    
    
    router.addRoute({
    
    
        name:"Admin",
        path:"/Admin",
        component:Admin
    })
    router.addRoute('Admin',{
    
    
        path:"Adminchild",
        component:Adminchild
    })
}

insert image description here
insert image description here
insert image description here

Delete route one
  • Add a route with the same name, and the latter can override the former route, which is equivalent to deleting the former route
    insert image description here
Delete route method 2
  • Through the removeRoute method, pass in the route name
router.removeRoute('home')
Delete route method three
  • The object stored in addRoute
const delrouter = router.addRoute({
    
    
    name: "home",
    path: '/home',
    component: Home,
    children: [
        {
    
    
            path: '/about',
            component: About
        }
    ]
})
delrouter()

Other Methods of Routing Objects

Check if the route exists
  • router.hasRoute
Get all mapped routing objects in the routing object
  • router.getRoutes()
console.log(router.getRoutes())

insert image description here

compile warning

insert image description here

Routing Navigation Guard

Front navigation guard
  • The navigation guard provided by vue-router is mainly used to guard the navigation by jumping or canceling
  • The global pre-guard beforeEach is called back when navigation is triggered
  • it has two parameters

  • to: the route object that is about to enter
  • from: Route object about to leave
  • There is also an optional third parameter next, which is used in vue2 to decide how to jump
  • it has return value

  • false, cancel the current navigation
  • Do not return or undefined, default navigation
  • return a routing address
  • Can be a string type path

  • It can be an object, which contains path, query, params and other information

// 路由导航拦截
// - 进行任何的路由跳转之前,传入到beforeEach中的函数都会被回调
router.beforeEach((to,from)=>{
    
    
    //不写条件会在登录页陷入死循环
    if(to.path!='/login'){
    
    
        return "/login"
    }
})
  • Common usage scenarios
  • Before entering the home page, determine whether the user is logged in
// 路由导航拦截
router.beforeEach((to, from) => {
    
    
    const token = localStorage.getItem("token")
    if (!token && to.path == '/home') {
    
    
        return "/login"
    }
    return undefined//否则默认导航
})
Complete navigation analysis process
  • 1. Navigation is triggered
  • 2. Call the beforeRouteLeave() guard in the deactivated component
  • 3. Call the global beforeEach() guard
  • 4. Call the beforeRouteUpdate() guard in the reused component, and the component instance this cannot be used
  • 5. Call beforeEnter() in the routing configuration
  • 6. Parse the asynchronous routing component ()=>import(…/xxx)
  • 7. Call beforeRouterEnter() in the activated component
  • 8. Call the global beforeReasolve(), after the component is parsed, before the jump
  • 9. Navigation is confirmed
  • 10. Call the global afterEach() hook,
  • 11. Trigger DOM update
  • 12. Call the callback function passed to next in the beforeRouteEnter() guard, and the created component instance will be passed in as a parameter of the callback function

Guess you like

Origin blog.csdn.net/weixin_44899940/article/details/132312005