i love lianghuilan...

vue-router 4.x

路由是什么

路由其实是网络工程中的一个术语:

  • 在建设一个网络时,非常重要的2个设备就是路由器交换机
  • 路由器主要维护了一个映射表
  • 映射表会决定数据的流向;

路由的概念在软件工程中出现,最早是在后端路由中实现的,原因就是web的发展主要经历了下面几个阶段:

  • 后端路由阶段;
  • 前后端分离阶段;
  • 单页面富应用(SPA);

后端路由阶段

早期的网站开发整个HTML页面是由服务器来渲染的.
服务器直接生产渲染好对应的HTML页面, 返回给客户端进行展示.

但是, 一个网站, 这么多页面服务器如何处理呢?

  • 一个页面有自己对应的网址, 也就是URL;
  • URL会发送到服务器, 服务器会通过正则对该URL进行匹配, 并且最后交给一个Controller进行处理;
  • Controller进行各种处理, 最终生成HTML或者数据, 返回给前端.

上面的这种操作, 就是后端路由

  • 当我们页面中需要请求不同的路径内容时, 交给服务器来进行处理, 服务器渲染好整个页面, 并且将页面返回给客户端.
  • 这种情况下渲染好的页面, 不需要单独加载任何的js和css, 可以直接交给浏览器展示, 这样也有利于SEO的优化.

后端路由的缺点:

  • 一种情况是整个页面的模块由后端人员来编写和维护的;
  • 另一种情况是前端开发人员如果要开发页面, 需要通过PHP和Java等语言来编写页面代码
  • 而且通常情况下HTML代码和数据以及对应的逻辑会混在一起, 编写和维护都是非常糟糕的事情;

前后端分离阶段

前端渲染的理解:

  • 每次请求涉及到的静态资源都会从静态资源服务器获取,这些资源包括HTML+CSS+JS,然后在前端对这些请求回来的资源进行渲染
  • 需要注意的是,客户端的每一次请求,都会从静态资源服务器请求文件
  • 同时可以看到,和之前的后端路由不同,这时后端只是负责提供API了

前后端分离阶段:

  • 随着Ajax的出现, 有了前后端分离的开发模式
  • 后端只提供API来返回数据,前端通过Ajax获取数据,并且可以通过JavaScript将数据渲染到页面中
  • 这样做最大的优点就是前后端责任的清晰,后端专注于数据上,前端专注于交互和可视化上
  • 并且当移动端(iOS/Android)出现后,后端不需要进行任何处理,依然使用之前的一套API即可
  • 目前比较少的网站采用这种模式开发(jQuery开发模式),操作DOM效率太低,更多都是基于三大框架开发SPA;

前端路由映射关系:路径 => 组件 之间的映射关系。

为什么需要前端路由呢?

因为传统的后端路由,url已发生改变,则需要请求静态资源服务器读取响应的页面,如果此时使用前端路由,按照 路径映射组件 的关系,前端直接切换组件即可实现页面的切换,无需请求静态服务器资源,因此大大提高网站效率和降低开发及维护成本。

URL的hash模式

前端路由是如何做到URL和内容进行映射呢?监听URL的改变。

URL的hash:

  • URL的hash也就是锚点(#), 本质上是改变window.location的href属性
  • 我们可以通过直接赋值location.hash来改变href, 但是页面不发生刷新;
  • hash的优势就是兼容性更好,在老版IE中都可以运行,但是缺陷是有一个#显得不像一个真实的路径

hash-demo.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <div id="app">
    <a href="#home">home</a>
    <a href="#login">login</a>

    <div class="content">Default</div>
  </div>


  <script>
    const contentEl = document.querySelector('.content')

    window.addEventListener('hashchange', function () {
      switch (location.hash) {
        case '#home':
          contentEl.textContent = "Home"
          break;
        case '#login':
          contentEl.textContent = "Login"
          break;
        default:
          contentEl.textContent = "Default"
      }
    })
  </script>
</body>

</html>

HTML5的history模式

history接口是HTML5新增的, 它有六种模式改变URL而不刷新页面

  1. replaceState:替换原来的路径;
  2. pushState:使用新的路径;
  3. popstate:监听历史记录的变化;
  4. go:向前或向后改变路径;
  5. forward:向前改变路径;
  6. back:向后改变路径;

html5-history-demo.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <div id="app">
    <a href="/home">home</a>
    <a href="/about">about</a>

    <div class="content">Default</div>

    <button class="backBtn">返回上一页</button>
    <button class="forwardBtn">前进</button>
  </div>


  <script>
    const contentEl = document.querySelector(".content")

    const changeContent = () => {
      switch (location.pathname) {
        case "/home":
          contentEl.textContent = "Home"
          break;
        case "/about":
          contentEl.textContent = "About"
          break;
        default:
          contentEl.textContent = "Default"
      }
    }

    // aEls是一个伪数组
    const aEls = document.getElementsByTagName("a")
    for (let aEl of aEls) {
      aEl.addEventListener('click', e => {
        // 取消a标签的默认跳转行为
        e.preventDefault()

        const href = aEl.getAttribute('href')
        history.pushState({}, "", href)
        changeContent();
      })
    }

    window.addEventListener('popstate', () => {
      console.log("popstate")
      changeContent()
    })

    document.querySelector('.backBtn').addEventListener('click', () => {
      console.log("返回上一页...")
      history.back()    // 等价于history.go(-1)
    })

    document.querySelector('.forwardBtn').addEventListener('click', () => {
      console.log("前进一页...")
      history.forward()    // 等价于history.go(1)
    })
  </script>

</body>

</html>

取消a元素的默认行为:event.preventDefalt()

上面2种方式都是为了不让浏览器刷新,防止浏览器重新请求静态资源。

认识vue-router

目前前端流行的三大框架, 都有自己的路由实现:

  • Angular的ngRouter
  • React的ReactRouter
  • Vue的vue-router

Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得非常容易。

目前Vue路由最新的版本是4.x版本,笔记基于最新的版本。

vue-router是基于路由和组件的:

  • 路由用于设定访问路径, 将路径和组件映射起来.
  • 在vue-router的单页面应用中, 页面的路径的改变就是组件的切换.

安装Vue Router:npm install vue-router@4

路由的基本使用和配置

配置步骤:

  1. 创建页面

    image-20211116082823269

    新建2个页面,About.vue、Home.vue;

  2. 配置路由映射表

    src/router/index.js

    import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
    
    // 引入组件
    import Home from '../pages/Home.vue'
    import About from '../pages/About.vue'
    
    // 配置映射关系
    const routes = [
      {path: '/home', component: Home},
      {path: '/about', component: About},
    ]
    
    // 创建路由对象router
    const router = createRouter({
      routes,
      // vue-router 4.x版本新增配置项
      history: createWebHashHistory()
    })
    
    export default router
    
  3. main.js中使用vue-router

    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router'
    
    const app = createApp(App)
    // 安装路由插件
    // app.use(router)
    // app.mount('#app')
    
    // 链式调用
    app.use(router).mount("#app")
    
    
  4. App.vue中设置路由占位符

    <template>
      <div>
        <router-link to="/home">Home</router-link>
        <router-link to="/about">About</router-link>
        
        <!-- 路由占位符 -->
        <router-view/>
      </div>
    </template>
    
    <script>
      export default {
      }
    </script>
    
    <style scoped>
    
    </style>
    

路由的默认路径

我们这里还有一个不太好的实现:

  • 默认情况下, 进入网站的首页, 我们希望<router-view>渲染首页的内容;
  • 但是我们的实现中, 默认没有显示首页组件, 必须让用户点击才可以;

如何可以让路径默认跳到到首页, 并且<router-view>渲染首页组件呢?

image-20211119085028350

我们在routes中又配置了一个映射:

  • path配置的是根路径: /
  • redirect是重定向, 也就是我们将根路径重定向到/home的路径下, 这样就可以得到我们想要的结果了.

router-link事实上有很多属性可以配置:

  • to属性:
    • 是一个字符串,或者是一个对象
  • replace属性:
    • 设置 replace 属性的话,当点击时,会调用 router.replace(),而不是 router.push();
  • active-class属性:
    • 设置激活a元素后应用的class,默认是router-link-active
  • exact-active-class属性:
  • 链接精准激活时,应用于渲染的 的 class,默认是router-link-exact-active;
<template>
  <div id="app">
    <router-link replace to="/home" active-class="lightpink">home</router-link>
    &nbsp;
    <router-link replace to="/about" active-class="lightpink">about</router-link>

    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {};
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {}
};
</script>

<style scoped ="less">
  .lightpink {
    color: lightpink;
    font-size: 18px;
    text-decoration: none;
  }
</style>

路由懒加载

异步组件和路由懒加载目的是为了减少打包的大小,加快首页渲染速度;

假设有10个页面,默认脚手架会全部打包(npm run build)到App.js文件中,部署到服务器,用户第一次访问的时候会下载整个App.js,这个文件是很大的,因此也会导致首页渲染变慢,因此官方推荐对路由进行懒加载配置,用到的时候再加载,等用户点到某个按钮要加载了或者用户的浏览器闲置的时候再加载。

未使用懒加载的打包效果:

image-20211116085454762

使用懒加载后的打包效果:

router.js

import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'

// 引入组件
// import Home from '../pages/Home.vue'
// import About from '../pages/About.vue'

/* 注意:
  import()写法是返回一个Promise对象,因此可以用于webpack分包
  import('../pages/About.vue').then(res => {
    
  })
*/

// 配置映射关系
const routes = [
  {path: '/', redirect: '/home'},
  {path: '/home', component: () => import("../pages/Home.vue")},
  {path: '/about', component: () => import("../pages/About.vue")},
]

// 创建路由对象router
const router = createRouter({
  routes,
  // vue-router 4.x版本新增配置项
  history: createWebHashHistory()
})

export default router

image-20211116090132614

看到chunk-xxx说明分包成功,懒加载路由对应的组件已经被分包处理,当用户访问具体路由时才会渲染。

如果想自定义打包后的分包文件名称则可以通过 魔法注释 实现

代码

router.js

// 配置映射关系
const routes = [
  {path: '/', redirect: '/home'},
  /* 对打包文件自定义名称,又称魔法注释,webpack内部会解析这些注释然后对打包文件名称进行命名 */
  {path: '/home', component: () => import(/* webpackChunkName: "home-chunk" */"../pages/Home.vue")},
  {path: '/about', component: () => import(/* webpackChunkName: "about-chunk" */"../pages/About.vue")},
]

实现效果:

image-20211116091021645

动态路由基本匹配

动态路由就是可以接收参数的路由、支持路径参数的路由。

很多时候我们需要将给定匹配模式的路由映射到同一个组件:

  • 例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但是用户的ID是不同的;

  • 在Vue Router中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数;

    image-20211119094959164

  • 在router-link中进行如下跳转:

image-20211119095009015

获取动态路由的值

那么在User中如何获取到对应的值呢?

在template中,直接通过 $route.params获取值;

  • 在created中,通过 this.$route.params获取值;
  • 在setup中,我们要使用 vue-router库给我们提供的一个hook useRoute;
  • 该Hook会返回一个Route对象,对象中保存着当前路由相关的值;

image-20211119095324647

image-20211119095327304

匹配多个参数

image-20211119100053597

image-20211119100129686

404配置

对于哪些没有匹配到的路由,我们通常会匹配到固定的某个页面:

  • 比如NotFound的错误页面中,这个时候我们可编写一个动态路由用于匹配所有的页面;

    image-20211119100521957

  • 我们可以通过 $route.params.pathMatch获取到传入的参数:

    image-20211119100600387

匹配规则加*

这里还有另外一种写法:

  • 注意:我在/:pathMatch(.*)后面又加了一个 *;

    image-20211119100744392

  • 它们的区别在于解析的时候,是否解析 /:

    image-20211119100804072

嵌套路由

image-20211119101942381

嵌套路由也称子级路由,上图显示我们为/home一级路由配置了2个二级路由,通过children进行配置,children是一个Array类型,需要注意的地方是:子级路由的path选项不需要加/,如果加了就会有问题

编程式导航

之前我们页面跳转是通过router-link来实现的,这种方式叫声明式导航,下面介绍使用编程式导航实现页面跳转

有时候我们希望通过代码来完成页面的跳转,比如点击的是一个按钮:

image-20211119102347087

当然,我们也可以传入一个对象:

image-20211119102355350

如果是在setup中编写的代码,那么我们可以通过 useRouter 来获取:

image-20211119102408202

demo

<template>
  <div>
    <h2>Home</h2>

    <div>
      <button @click="showProduct">product</button>
      <button @click="showMessage">message</button>
    </div>

    <router-view></router-view>
  </div>
</template>

<script>
  import {useRouter, routerKey} from 'vue-router'
  export default {
/*     methods: {
      showProduct() {
        // this.$router.push('/home/product')
        this.$router.push({
          path: '/home/product'
        })
      },
      showMessage() {
        // this.$router.push('/home/message')
        this.$router.push({
          name: 'homeMessage'
        })
      }
    }, */
    setup() {
      const $router = useRouter()

      const showProduct = () => {
        $router.push({
          path: '/home/product'
        })
      }

      const showMessage = () => {
        $router.push({name: 'homeMessage'})
      }

      return {
        showProduct,
        showMessage
      }
    }
  }
</script>

<style scoped>

</style>

注意区分$router$route

  • $router:可以理解成管理路由的对象,用来做路由跳转、传参、前进、后退;
  • $route:用于获取某条路由的详细信息,例如路由meta、name、path、参数等;

query方式传递参数

我们也可以通过query的方式来传递参数:

image-20211119104419657

在界面中通过 $route.query 来获取参数:

image-20211119104428449

demo

<template>
  <div>
    <h2>Home</h2>

    <div>
      <button @click="showProduct">product</button>
      <button @click="showMessage">message</button>
    </div>

    <router-view></router-view>
  </div>
</template>

<script>
  import {useRouter, routerKey} from 'vue-router'
  export default {
/*     methods: {
      showProduct() {
        // this.$router.push('/home/product')
        this.$router.push({
          path: '/home/product'
        })
      },
      showMessage() {
        // this.$router.push('/home/message')
        this.$router.push({
          name: 'homeMessage'
        })
      }
    }, */
    setup() {
      const $router = useRouter()

      const showProduct = () => {
        $router.push({
          // path: '/home/product',
          name: 'homeProduct',
          /* 
            如果使用params方式传参,就不能使用path来设置路径;
            要使用name,因为设置了path,params就会被忽略
          */
          params: {name: "Alexander", age: 24, hasGirlFriend: true}
        })
      }

      const showMessage = () => {
        $router.push({name: 'homeMessage'})
      }

      return {
        showProduct,
        showMessage
      }
    }
  }
</script>

<style scoped>

</style>

替换当前的位置

使用push的特点是压入一个新的页面,那么在用户点击返回时,上一个页面还可以回退,但是如果我们希望当前页面是一个替换操作,那么可以使用replace:

image-20211119104631111

页面的前进后退

router的go方法:

image-20211119105456495

router也有back:

  • 通过调用 history.back() 回溯历史。相当于 router.go(-1);

router也有forward:

  • 通过调用 history.forward() 在历史中前进。相当于 router.go(1);

router-link的v-slot

下面介绍router-linkrouter-viewvue-router4.x的新特性。

image-20211117015053988

router-link、router-view这类全局组件的原理其实就是vue在通过createApp函数创建了app对象之后通过use的方式注册了vue-router插件,vue-router插件的install函数中会注册router-link、router-view 2个全局component,因此我们就可以在组件中直接使用。

在vue-router3.x的时候,router-link有一个tag属性,可以决定router-link到底渲染成什么元素:

  • 但是在vue-router4.x开始,该属性被移除了;
  • 而给我们提供了更加具有灵活性的v-slot的方式来定制渲染的内容;

v-slot如何使用呢?

  • 首先,我们需要使用custom属性表示我们整个元素要自定义;
  • 如果不写,那么自定义的内容会被包裹在一个 a 元素中;
  • 其次,我们使用v-slot来作用域插槽来获取内部传给我们的值:
  • href:解析后的 URL;
  • route:解析后的规范化的route对象;
  • navigate:触发导航的函数;
  • isActive:是否匹配的状态;
  • isExactActive:是否是精准匹配的状态;

demo

<router-link replace to="/about" active-class="lightpink" custom v-slot="props">
  <div>v-slot props: {{Object.keys(props)}}</div>
  <p>href: {{props.href}}</p>
  <p>route: {{props.route}}</p>
  <p>isActive: {{props.isActive}}</p>
  <p>isExactActive: {{props.isExactActive}}</p>
  <p>navigate: {{props.navigate}}</p>
  <button @click="props.navigate">跳转About</button>
</router-link>

页面效果:

image-20211119112802675

router-view的v-slot

router-view也提供给我们一个插槽,可以用于 组件来包裹你的路由组件:

  • Component:要渲染的组件;
  • route:解析出的标准化路由对象;

image-20211120000330193

image-20211120000333297

注意:<keep-alive></keep-alive>标签内不能写注释,否则会报下面错误:

VueCompilerError: <KeepAlive> expects exactly one child component.

动态添加路由

某些情况下我们可能需要动态的来添加路由:

  • 比如根据用户不同的权限,注册不同的路由;
  • 这个时候我们可以使用一个方法 addRoute;

如果我们是为route添加一个children路由,那么可以传入对应的name:

image-20211120000855001

添加一个一级路由,路由路径为/category

image-20211120000900207

给名称为home的一级路由添加一个子路由homeMomentRoute

应用场景

例如后台管理系统的权限设计:

账号 => 角色 => 权限 => 不同的路由;

我们一开始不能把路由写死,需要根据用户角色对应的权限进行动态注册路由。

demo

const routes = []
const router = createRouter({routes})

if (role === '管理员') {
	router.addRoute({path: "/order"}, component: () => import('./pages/order.vue'))
}

if (role === '销售') {
	// ...
}

if (role === '运营') {
	// ...
}

app.use(router)

router.js

// 引入组件
import {
  createRouter,
  createWebHashHistory,
  createWebHistory
} from 'vue-router'

// 配置映射关系
const routes = [{
    path: "/home",
    name: 'home',
    component: () => import('../pages/Home.vue'),
    children: [
      {
        path: '',
        redirect: '/home/product'
      },
      {
        path: 'product',
        name: 'homeProduct',
        component: () => import('../pages/HomeProduct.vue')
      },
      {
        path: 'message',
        name: "homeMessage",
        component: () => import('../pages/HomeMessage.vue')
      }      
    ]
  },
  {
    path: "/about",
    component: () => import('../pages/About.vue')
  },
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: '/user/:id/info/:name',
    component: () => import('../pages/User.vue')
  }, 
  {
    path: '/:pathMatch(.*)*',
    component: () => import('../pages/404.vue')
  }
]



// 创建路由对象router
const router = createRouter({
  routes,
  // hash模式
  // history: createWebHashHistory()
  // history模式
  history: createWebHistory()
})

// 动态添加路由
console.log("正在添加路由~")

const categoryRoute = {
  path: '/category',
  component: () => import('../pages/Category.vue')
}

const homeMomentRoute = {
  path: 'moment',
  component: () => import('../pages/HomeMoment.vue')
}

setTimeout( () => {
  // 添加一级路由
  router.addRoute(categoryRoute)
  // 给home一级路由添加一个子路由
  router.addRoute('home', homeMomentRoute)
  console.log("[+] add route success")
}, 2000)

export default router

动态删除路由

删除路由有以下三种方式:

  • 方式一:添加一个name相同的路由;

    image-20211120012141455

  • 方式二:通过removeRoute方法,传入路由的名称;

    image-20211120012209046

  • 方式三:通过addRoute方法的返回值回调;

    image-20211120012217869

路由的其他方法补充:

  • router.hasRoute():检查路由是否存在。

    console.log("检查about路由是否存在: ", router.hasRoute('category'))

  • router.getRoutes():获取一个包含所有路由记录的数组。

路由导航守卫

vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。

全局的前置守卫beforeEach是在导航触发时会被回调的:

它有两个参数:

  • to:即将进入的路由Route对象;
  • from:即将离开的路由Route对象;

它有返回值:

  • false:取消当前导航;
  • 不返回或者undefined:进行默认导航;
  • 返回一个路由地址:
    • 可以是一个string类型的路径;
    • 可以是一个对象,对象中包含path、query、params等信息;

可选的第三个参数:next:

  • 在Vue2中我们是通过next函数来决定如何进行跳转的;
  • 但是在Vue3中我们是通过返回值来控制的,不再推荐使用next函数,这是因为开发中很容易调用多次next;

image-20211120013648552

导航守卫在登录功能应用

比如我们完成一个功能,只有登录后才能看到其他页面:

image-20211120015014991

Login.vue

image-20211120015018208

其他导航守卫

Vue还提供了很多的其他守卫函数,目的都是在某一个时刻给予我们回调,让我们可以更好的控制程序的流程或者功能:

文档地址:https://next.router.vuejs.org/zh/guide/advanced/navigation-guards.html

完整的导航解析流程:

  • 导航被触发;
  • 在失活的组件里调用 beforeRouteLeave 守卫;
  • 调用全局的 beforeEach 守卫;
  • 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+);
  • 在路由配置里调用 beforeEnter;
  • 解析异步路由组件;
  • 在被激活的组件里调用 beforeRouteEnter;
  • 调用全局的 beforeResolve 守卫(2.5+);
  • 导航被确认;
  • 调用全局的 afterEach 钩子;
  • 触发 DOM 更新
  • 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入;

总结

vue-router 4.x

posted @ 2021-11-20 02:28  c4az6  阅读(700)  评论(0编辑  收藏  举报