Vue基础——(超详细)前端路由跳转(vue-router)

作者 : admin 本文共6467个字,预计阅读时间需要17分钟 发布时间: 2024-06-16 共1人阅读

(超详细)前端路由跳转——vue-router

文章目录

  • (超详细)前端路由跳转——vue-router
    • 一、什么是路由
    • 二、使用方法
      • 1.安装路由并配置:
        • 1.1下载vue-router插件到当前工程
        • 1.2创建router/index.js文件
        • 1.3在main.js中引用router
      • 2.基本使用:
        • 2.1声明式(router-link)跳转:
        • 2.2编程式跳转
      • 3.路由传参与接收:
        • 3.1路由传参——query:
        • 3.2路由传参——params:
        • 3.3接收路由参数:
        • 3.4路由传参与接收——props:
      • 4.嵌套路由(套娃):
      • 5.\的相关属性:
        • 5.1 replace属性(push同理)
        • 5.2 tag属性
        • 5.3 append属性
        • 5.4 前进与后退属性
          • 5.4.1 前进:
          • 5.4.2 后退:
      • 6.两个新的生命周期钩子
    • 三、路由守卫
      • 1.全局守卫——beforeEach、afterEach、beforeResolve(2.5.0新增)
      • 2.独享守卫——beforeEnter
      • 3.组件内守卫——beforeRouteEnter、beforeRouteUpdate(2.2新增)、beforeRouteLeave
    • 四、路由模式
    • 补充:
      • 1.query传参和params传参的区别?
      • 2.路由懒加载
    • 总结:

如果想看MD文档的
点击这里下载,MD的看的舒适点

一、什么是路由

vue-router是vue的一个插件库,专门用来实现SPA应用

SPA:

  1. 单页Web应用(single page web application)
  2. 整个应用只有一个完整的页面
  3. 点击页面中的导航链接不会刷新页面,只会做页面的局部更新
  4. 数据需要通过api接口请求获取
  • 一个路由就是一组映射关系(key-value)
  • key为路径,value可能是function或component

二、使用方法

1.安装路由并配置:

1.1下载vue-router插件到当前工程
yarn add vue-router
npm install vue-router@3||4 //3是vue2,4是vue3
1.2创建router/index.js文件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Page1 from "@/pages/Page1"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Page1',
    component: Page1,
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

1.3在main.js中引用router
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: ''
})

2.基本使用:

2.1声明式(router-link)跳转:

router/index.js的配置如下:

import Vue from 'vue'
import VueRouter from 'vue-router'
import IndexPage from "@/pages/Index"
import Page1 from "@/pages/Page1"
import Page2 from "@/pages/Page2"
const routes = [
  {
    path: '/',
    name: 'IndexPage',
    component: IndexPage,
    children:[
      {
        path:'page1',
        component:Page1,
      },
      {
        path:'page2',
        component:Page2
      }
    ]
  },
]
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

export default router

代码如下:

<template>
    <div>
        <div class="btn">
            <router-link to="/page1">页面1</router-link>
            <router-link to="/page2">页面2</router-link>
        </div>
        <div class="content">
            <router-view />  
        </div>
    </div>
</template>

router-link实质上最终会渲染成a链接,to属性等价于a链接的href属性

2.2编程式跳转

$router操作路由跳转:

this.$router.push({ name:‘page1’, query:{ name:‘张三’, age:11} })

$route读取路由参数接收:

let name = this.$route.query.name;
let age = this.$route.query.age;

3.路由传参与接收:

3.1路由传参——query:

代码如下:



<router-link to="/page1?name='张三'&age=18">页面1</router-link>

<router-link :to="{
                  	name:'page1', // 或者用 path:'/page1'
                    query:{
                       name:'张三',
                       age:18
                    }
              }">页面1</router-link>
3.2路由传参——params:


<router-link to="/page1/张三/18">页面1</router-link> //路由path中配置path:'page1/:name/:age'

<router-link :to="{
                  	name:'page1', //这里只能用name不能用path
                    params:{
                       name:'张三',
                       age:18
                    }
              }">页面1</router-link>
3.3接收路由参数:
<!------------ 接收 ------------->
this.$route.query //objec====》{name:'张三',age:18}
this.$route.params //objec====》{name:'张三',age:18}
3.4路由传参与接收——props:
//在index.js中
	  {
        path:'page1',
        component:Page1,
        //方式一
        props:{name:'张三',age:18},
        //方式二
        props:true,
        //方式三
        props($route){
            return {
                name:$route.query.name,
                age:$route.query.age
            }
        }
      },
          
//接收
props:['name','age']

4.嵌套路由(套娃):

const routes = [
  {
    path: '/',
    name: 'Page1', //一级路由
    component: Page1,
    children:[
      {
        path:'children1', //二级路由(二级以下路由不能加/)
        component:children1,
        children:[
          {
            name:'children1-1',
            path:'children1-1', //三级路由
            component:children1-1
          }
        ]
      },
    ]
  },
]

5.的相关属性:

5.1 replace属性(push同理)

1.作用:控制路由跳转时操作浏览器历史记录的模式

2.浏览器的历史记录有两种写入方式:分别是push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push

3.如何开启replace模式:

<router-link replace ........>content</router-link>  
<script>
	this.$router.replace("/page1")   //编程式操作
</script>
5.2 tag属性

1.作用:将渲染成自己想要的标签

2.使用格式:

<router-link to="/page1" tag="button">按钮</router-link>

<button>按钮</button>
5.3 append属性

1.作用:设置链接激活时使用的css类名

2.使用格式:

<router-link to="/page1" active-class="active">页面1</router-link>
<router-link to="/page2" active-class="active">页面2</router-link>
<style scoped>
.active{
 background-color: #20c2eb;
 border-radius: 10%;
 border: 1px solid #000;
}
</style>
5.4 前进与后退属性
5.4.1 前进:
$router.forward() //前进1
$router.go(1) //前进1
$router.go(3) //前进3
5.4.2 后退:
$router.back()	//后退1
$router.go(-1)	//后退1
$router.go(-3)	//后退3

6.两个新的生命周期钩子

1.作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态

2.具体名字:

​ 1.activated:路由组件被激活时触发

​ 2.deactivated:路由组件失活时触发

三、路由守卫

1.作用:对路由进行权限控制

2.分类:全局守卫、独享守卫、组件内守卫

1.全局守卫——beforeEach、afterEach、beforeResolve(2.5.0新增)

代码如下:

//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next) => {
  if (to.meta.isAuth) { //鉴定是否需要权限
    if (localStorage.getItem("userType") === 2) { //判断用户类型=》0:管理员,1:普通用户,2:VIP
      next() //放行
    }else{
      alert('请充值会员访问!')
    }
  }else{
    next() //放行
  }
});

//全局后置路由守卫——初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from) => {
    if(to.meta.title){
        document.title = to.meta.title //修改网页的title
    }
});

2.独享守卫——beforeEnter

代码如下:

//在router/index.js中
{
    path:'page1',
    component:Page1,
    meta:{title:'页面1'},
    beforeEnter:(to,from,next) => {
    if (to.meta.isAuth) { //鉴定是否需要权限
      if (localStorage.getItem("userType") === 2) { //判断用户类型=》0:管理员,1:普通用户,2:VIP
          next() //放行
      }else{
          alert('请充值会员访问!')
       }
    }else{
        next() //放行
    }
    }
}

注意:独享守卫只有beforeEnter

3.组件内守卫——beforeRouteEnter、beforeRouteUpdate(2.2新增)、beforeRouteLeave

<script>
export default {
    name: 'page1',
    //进入守卫,通过路由规则,进入该组件时被调用
    beforeRouteEnter(to, from, next) {
        console.log('通过路由规则,进入组件之前调用');
        next()
    },
    beforeRouteUpdate(to, from, next) {
	    // 在当前路由改变,但是该组件被复用时调用
	    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
	    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
	    // 可以访问组件实例 `this`
	  },
    //离开守卫,通过路由规则,离开该组件时被调用
    beforeRouteLeave(to,from,next){
        console.log('通过路由规则,离开组件时调用');
        next()
    }
};
</script>

四、路由模式

1.对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值

2.hash值不会包含在HTTP请求中,即:hash值不会带给服务器

3.hash模式:

1.地址中永远带着#号,不太美观

2.若以后将地址通过第三方手机APP分享,若APP校验严格,则地址会被标记为不合法

3.兼容性好

4.history模式:

1.地址干净,美观

2.兼容性和hash模式相比略差

3.应用部署上线时需要后端人员支持,解决刷新页面服务器404的问题

补充:

1.query传参和params传参的区别?

1、query传参刷新页面数据不会丢失,而params传参刷新页面数据会丢失;

2、query 可以通过path和name传参,而 params只能使用name传参;

3、query传递的参数会显示在地址栏中,而params传参不会;

4、params可以搭配动态路由传参,动态传参的数据会显示在地址栏中,且刷新页面不会消失,而query不可以;

2.路由懒加载

没有使用懒加载的情况下:

const routes = [
  {
    path: '/',
    name: 'IndexPage',
    component: IndexPage,
    children:[
      {
        path:'page1',
        component:Page1,
        children:[
          {
            name:'One',
            path:'one',
            component:One,
          }
        ]
      },
      {
        path:'page2',
        component:Page2,
      }
    ]
  },
]

Vue基础——(超详细)前端路由跳转(vue-router)插图

每次进入新页面都不会加载新的js包,说明第一次页面加载时已经加载了所有的js包了

使用懒加载后:

const routes = [
  {
    path: '/',
    name: 'IndexPage',
    component: ()=>import('../pages/Index'),
    meta:{title:'首页'},
    children:[
      {
        path:'page1',
        component:()=>import('../pages/Page1'),
        meta:{title:'页面1'},
        children:[
          {
            name:'One',
            path:'one',
            component:()=>import('../pages/One'),
            meta:{isAuth:true,title:'详情'}
          }
        ]
      },
      {
        path:'page2',
        component:()=>import('../pages/Page2'),
        meta:{title:'页面2'}
      }
    ]
  },
]

Vue基础——(超详细)前端路由跳转(vue-router)插图(1)

使用懒加载之后每次只加载需要的js包,当加载子组件时才加载子组件的包,重复点击也不会重新加载js包,这样做可以让js包很大的时候起到加载白屏时间减少的作用

总结:

vue-router是vue的一个插件库,专门用来实现SPA应用,有声明式编程式跳转,传参有query和params两种,路由可以进行套娃进行子路由的配置,一般套4-5层左右。路由有两个新的生命周期钩子activated和deactivated;本文重点是路由守卫,有全局守卫(前置beforeEach、后置afterEach、beforeResolve)、组件内守卫(beforeRouteEnter、beforeRouteLeave、beforeRouterUpdate)、独享守卫(beforeEnter)。最后,路由模式涉及到项目上线,所以要根据自己的需求和后端人员沟通好来决定用什么模式。

本站无任何商业行为
个人在线分享 » Vue基础——(超详细)前端路由跳转(vue-router)
E-->