Vue router learning (personal study notes 4)

friendly reminder

First look at the article directory to get a general understanding of the structure of the knowledge points. You can directly click on the article directory to jump to the specified location of the article.

Chapter 1, Introduction to Routing

1.1) What is routing

① A route is a set of mapping relationships (key - value), where the key is the path and the value may be a function (method) or component (component).
②Classification of routing:
1. Back-end routing: For example: @RequestMapping, understanding: value is a function (method), used to process the request submitted by the client. Working process: When the server receives a request, it finds a matching function according to the request path to process the request and returns the response data.
2. Front-end routing: router, understanding: value is a component (component), used to display page content. Working process: When the path of the browser changes, the corresponding component will be displayed.
insert image description here

1.2) Install the routing plugin

①Execute the command in Terminal

命令:npm i vue-router

insert image description here

② An error was reported, because version 4 of vue-router is installed by default, and this version can only be used in vue3. In
Vue2, we should install version 3 of vue-router

insert image description here
③ Execute the command to install version 3, and the installation is successful

命令:npm i vue-router@3

insert image description here

Chapter 2, Custom Router

2.1) Create the router file index.js file

insert image description here

2.2) Configure routing information in the index.js file

//我们在这里写路由信息
//引入路由包
import VueRouter from "vue-router"
//引入组件地址
import LoginDemo from "../components/Login"
import RegDemo from "../components/Reg"
import CodeLogin from "../components/login/CodeLogin"
import PhoneLogin from "../components/login/PhoneLogin"
import Main from "../components/Main"
//创建路由器对象
export  default  new VueRouter({
    
    
    //配置路由信息  routes  多组路由信息
    routes:[
        //配置默认加载组件
        {
    
    
            path:"/",//当请求是跟路径请求是  直接发起/loginPath请求
            redirect:"/loginPath"
        },
        //路由的信息写在路由对象中
        {
    
    
            //一级路径  在跟路径下直接访问  需要加载到app.vue中
            path:"/loginPath",//某个组件的访问路径  /代表根路径 http://ip:port/loginPath
            //对应的组件
            component:LoginDemo,
            children:[//配置当前路由的子路由
                {
    
    
                    //二级三级路由不能写/前缀
                    path:"codeLoginPath",//该路由是二级路由  由一级路由发起  /loginPath/codeLoginPath
                    name:"codeLoginName",//当前二级的名字
                    component:CodeLogin
                },
                {
    
    
                    path:"phoneLoginPath",
                    component:PhoneLogin
                }
            ]
        },
        {
    
    
            path:"/regPath",
            component:RegDemo
        },
        {
    
    
            path:"/mainPath",
            component:Main
        }
    ],
    //路由器是前端路由  为了和后台请求区别  当前请求访问的是前端组件
    //mode属性可以设置不显示#路径前缀
    mode:"history" //默认mode是hash  浏览器路径中会有#   设置为history 就不再显示#
})

Chapter 3, Using the Router

3.1) Bind the router to the Vue object in the main.js file

When the router is bound to the Vue object, all components under it have the router function

import Vue from 'vue'
import App from './App.vue'
//把路由器绑定到vue对象身上
//1 引入路由器组件
import VueRouter from "vue-router"
//2 引入我们自己写的路由器js文件
import MyRouter from "./router/index"
//3 让vue对象有路由器功能
Vue.use(VueRouter)
Vue.config.productionTip = false

new Vue({
    
    
  render: h => h(App),
  //把我们写好的路由器  放在vue对象上
  Router:MyRouter,
  data(){
    
    
    console.log("这是vue对象:",this)
    return{
    
    }
  }
}).$mount('#app')

3.2) Initiate a routing request on the App.vue root component

By initiating a routing request on the component, and indicating where the general component corresponding to this route is loaded (indicate whether to load on the App.vue root component or on the general component)

<template>
  <div id="app">
      <!--通过发起路由请求  加载对应的组件,在index.js配置了映射-->
      <!--<a href="/loginPath">登录</a>
      <a>注册</a>
      <hr/>-->
      <!--router-link是路由连接请求  它会被vue对象编译成a标签-->
      <router-link to="/loginPath">登录</router-link>
      <router-link to="/regPath">注册</router-link>
      <hr/>
      <!--router-view指路由连接请求对应的组件展示位置-->
     <router-view></router-view><!--  一级路由展示位置  -->
  </div>
</template>

<script>
export default {
    
    
  name: 'App',
}
</script>
<style>
</style>

2.5) The three components corresponding to the first-level routing

2.5.1) login.vue

Load the first-level routing component to the root route

<template>
    <div>
        <center>
            <router-link to="/loginPath/codeLoginPath">账号密码登录</router-link>
            <router-link to="/loginPath/phoneLoginPath">手机号登录</router-link>/
            <router-link to="/mainPath">去首页</router-link>
            <br/>
            <router-link :to="{name:'codeLoginName'}">根据名字账号密码登录</router-link>/
            <router-link to="/loginPath/phoneLoginPath">手机号登录</router-link>
            <button @click="goToMain()">去首页</button>
            <hr/>
            <router-view></router-view><!--  二级路由展示位置 -->
        </center>
    </div>
</template>

<script>
    export default {
    
    
        name: "LoginDemo",
        data(){
    
    
            console.log("这是loginDemo的VC对象:",this)
            return{
    
    }
        },
        methods:{
    
    
            goToMain(){
    
    
                //使用路由跳转到首页
               //this.$router.push("/mainPath") // push是加入一个新路径
                alert("通过this.$router进行路由跳转")
                this.$router.replace("/mainPath")//替换当前路径
            }
        }
    }
</script>

<style scoped>

</style>

2.5.2)reg.view

<template>
    <div>
        <center>
            <h1>欢迎使用注册组件</h1>
            <from>
                账号:<input type="text" name="loginCode"/><br/>
                密码:<input type="text" name="loginPwd"/><br/>
                <input type="button" value="注册"/><br/>
            </from>
            <a>去登录</a>
        </center>
    </div>
</template>

<script>
    export default {
    
    
        name: "RegDemo"
    }
</script>

<style scoped>

</style>

2.5.3)main.view

<template>
    <div>
        <h1>欢迎XXX访问首页</h1>
    </div>
</template>

<script>
    export default {
    
    
        name: "MainDemo"
    }
</script>

<style scoped>

</style>

2.6) Components corresponding to the secondary routing

Load the secondary routing component into the primary routing component

2.6.1) CodeLogin.vue

<template>
    <div>
        <h1>账号密码登录组件</h1>
        <form>
            账号:<input type="text" name="loginCode"/><br/>
            密码:<input type="text" name="loginPwd"/><br/>
            <input type="button" value="登录"/><br/>
        </form>
       <router-link to="/regPath">去注册</router-link>
    </div>
</template>

<script>
    export default {
    
    
        name: "CodeLogin"
    }
</script>

<style scoped>

</style>

2.6.2) PhoneLogin.vue

<template>
    <div>
        <h1>手机验证码登录组件</h1>
        <form>
            账号:<input type="text" name="loginCode"/><br/>
            密码:<input type="text" name="loginPwd"/><br/>
            <input type="button" value="登录"/><br/>
        </form>
        <router-link to="/regPath">去注册</router-link>
        <hr/>
        <!--加载三级路由组件-->
        <router-view></router-view><!--  三级路由展示位置 -->
    </div>
</template>

<script>
    export default {
    
    
        name: "PhoneLogin"
    }
</script>

<style scoped>

</style>

Chapter 3, Routing Component Details

3.1) Naming of routing components

Configure the name of the route in index.js

children:[//配置当前路由的子路由
                {
    
    
                    //二级三级路由不能写/前缀
                    path:"codeLoginPath",//该路由是二级路由  由一级路由发起  /loginPath/codeLoginPath
                    name:"codeLoginName",//当前二级的名字
                    //对应的组件
                    component:CodeLogin
                },
                {
    
    
                    path:"phoneLoginPath",
                    component:PhoneLogin
                }
            ]
        }

replace path with name

<router-link to="/loginPath/codeLoginPath">账号密码登录</router-link>
            <router-link to="/loginPath/phoneLoginPath">手机号登录</router-link>/
            <router-link to="/mainPath">去首页</router-link>
            <br/>
            <router-link :to="{name:'codeLoginName'}">账号密码登录</router-link>/
            <router-link to="/loginPath/phoneLoginPath">手机号登录</router-link>
            <button @click="goToMain()">去首页</button>

3.2) Routing jump mode

common way to jump

<router-link to="/mainPath">去首页</router-link>

Add a click event to the button: @click

<button @click="goToMain()">去首页</button>

By clicking event, replace the current path, or add a new path.

 methods:{
    
    
            goToMain(){
    
    
                //使用路由跳转到首页
                //this.$router.push("/mainPath") // push是加入一个新路径
                alert("通过this.$router进行路由跳转")
                this.$router.replace("/mainPath")//替换当前路径
            }
        }

Chapter 4, Routing Guard

4.1) Introduction to Routing Guard

①Routing guard is a method of pre- and post-intercepting all routing requests
②Routing guard is a set of functions that can monitor routing changes and control routing jumps, and can be used to verify the authority of pages before/after routing jumps , state interception and other operations, thereby enhancing the security and controllability of page interaction.
③ Route guards include three types: global guards, guards exclusive to a single route, and guards within components. Mainly learn global routing guards

4.2) Configure the global routing guard in the index.js file

import VueRouter from "vue-router"
import Main from "../components/Main"

const MyVueRouter = new VueRouter({
    
    
    routes:[
        {
    
    
            path:"/",
            redirect:"/loginPath"
        },
        {
    
    
            path:"/loginPath",
            component:()=>import("../components/Login.vue"),
            meta:{
    
    
                titleName:"登录"
            }
        },
        {
    
    
            path:"/mainPath",
            component:Main,
            meta:{
    
    
                //meta属性 是我们自定义属性 你想写什么就写什么
                love:false,
                titleName:"首页"
            },
            //独享路由守卫  只有前置路由守卫
            beforeEnter:((to, from, next)=>{
    
    
                console.log("独享路由守卫to:",to)
                console.log("独享路由守卫from:",from)
                console.log("独享路由守卫next:",next)
                //可以根据to的name  path来判断是否放行   组件较多使用meta来提供标识
                if(to.meta.love=="true"){
    
    
                    next();
                }else{
    
    
                    next("/loginPath");//强行去登录页面
                }
            })
        },
        {
    
    
            path:"/empPath",
            component:()=>import("../components/Emp.vue"),
            meta:{
    
    
                titleName:"员工管理"
            }
        }
    ],
    mode:"history"
});
//全局路由守卫
//前置路由守卫  每一个路由请求请求路由器时  前置路由守卫都会进行拦截
MyVueRouter.beforeEach(function(to,from,next){
    
    
    //to:你要访问哪个路由
    //from:你这个请求从哪来
    //next:是否让该请求通过
    console.log("我是全局前置路由守卫,只要有人发起对路由器的路由请求 我都能监听到")
    console.log("你这个请求从哪来:from:",from)
    console.log("你要到哪去:to:",to)
    console.log("next有什么用:next:",next)
    //当有人访问mainPath  需要验证账号是否登录
    if(to.meta.love==false){
    
    
        alert("没有登录不能访问首页");
    }else{
    
    
        next();//放行函数
    }
})
//全局路由后置守卫
MyVueRouter.afterEach(function(to,from){
    
    
    console.log("我是后置路由守卫,你从哪来 from:",from)
    console.log("我是后置路由守卫,你到哪来 to:",to)
    //一般我们在后置路由守卫中修改页面的title值
    window.document.title=to.meta.titleName
})
//对外声明该路由器对象
export default MyVueRouter

4.3) Exclusive route guard and component guard (understand)

4.3.1) Exclusive route guard

① Meaning: A route guard unique to a certain route, the api name is beforeEnter A
guard exclusive to a single route refers to a function defined only for a single route, which can be used to perform special control and operations on the route. More fine-grained than global guards.
②beforeEnter(to, from, next): Executed before the route jumps, the usage is the same as the global front guard, but it is only valid for the current route.
③Exclusive route guard only has beforeEnter, no post guard
beforeEnter and global post guard can be used at the same time without conflict!

{
    
    
//这个组件的访问路径
path:"/login",
component:LoginDemo,
    children:[
        {
    
    
            path:"codeLogin",
            component:()=>import("../components/CodeLogin"),
            meta:{
    
    isAuth:true},
            beforeEnter:((to, from, next)=>{
    
    
                console.log("独享路由守卫to:",to)
                console.log("独享路由守卫from:",from)
                console.log("独享路由守卫next:",next)
                //可以根据to的name  path来判断是否放行   组件较多使用meta来提供标识
                if(to.meta.isAuth){
    
    
                    next();
                }else{
    
    
                    next("/login");//强行去登录页面
                }
            })
        },

4.3.1) Component route guard

①In-component routing guards are to write code inside the component to implement permission management. If the component has its own separate permission logic, these two routing guards can be used. ②Entering guards: through routing rules,
beforeRouteEnter
( to, from, next) { },
③Leave guard:
beforeRouteLeave (to, from, next) { } is called when leaving the component through routing rules

<template>
  <div>
    我是User的内容
  </div>
</template>

<script>
export default {
    
    
  name:'UserDemo',
  // 进入守卫:通过路由规则,进入该组件时被调用
  beforeRouteEnter (to, from, next) {
    
    
    console.log("beforeRouteEnter被调用")
    if(to.meta.isAuth){
    
    
      if(localStorage.getItem('username') === "大郎"){
    
    
        next()
      }else{
    
    
        alert('用户名不正确,没有权限查看!')
      }
    }else{
    
    
      next()
    }
  },
  //离开守卫:通过路由规则,离开该组件时被调用
  beforeRouteLeave (to, from, next) {
    
    
    console.log("beforeRouteLeave被调用",to,from)
    next()
  }
}
</script>
<style scoped>
</style>

Guess you like

Origin blog.csdn.net/baomingshu/article/details/131848698