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

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


如果想看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: '<App/>'
})

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 />  <!-- 点击页面1通过to的path路径把相对于的组件渲染到该区域 -->
        </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.<router-link>的相关属性:

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.作用:将<router-link />渲染成自己想要的标签

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,
      }
    ]
  },
]

在这里插入图片描述

每次进入新页面都不会加载新的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'}
      }
    ]
  },
]

在这里插入图片描述

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

总结:

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

  • 47
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3 中,你可以使用 Vue Router 进行。下面是一些基本的步骤: 1. 首先,确保你已经安装了 Vue Router。你可以通过运行以下命令来安装它: ``` npm install vue-router@next ``` 2. 在你的主文件(例如 `main.js` 或 `main.ts`)中导入 Vue Router 和你的由配置: ```javascript import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import App from './App.vue'; import Home from './views/Home.vue'; import About from './views/About.vue'; const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp(App); app.use(router); app.mount('#app'); ``` 在上面的示例中,我们创建了两个由:`/` 对应 `Home` 组件,`/about` 对应 `About` 组件。你可以根据自己的需求添加更多的由。 3. 在你的组件中使用,你可以使用 `<router-link>` 组件或 `$router.push` 方法。 使用 `<router-link>` 组件: ```html <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> ``` 使用 `$router.push` 方法: ```javascript // 在方法中调用 methods: { goToHome() { this.$router.push('/'); }, goToAbout() { this.$router.push('/about'); } } // 或者在模板中调用 <button @click="$router.push('/')">Go to Home</button> <button @click="$router.push('/about')">Go to About</button> ``` 这样,当用户点击链接或按钮时,由就会进行。 这只是一个基本的示例,你还可以使用更多的 Vue Router 功能,如由参数、嵌套由、由守卫等。你可以参考 Vue Router 的官方文档来了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值