Vue Router是Vue.js的官方路由器。为了更轻易构建SAP单页应用(single page application)
多页面应用:有多个html文件,通过a标签的连接联通各个页面 缺点:
- 开发起来太冗余,编译、压缩很耗时间
- 页面之间的跳转速度慢,跳转间隙会出现白屏,用户体验差
单页面应用:
- 解决多页面应用的问题。只有一个页面,无需刷新页面
- 必须依靠路由来实现内容切换,app、后台管理系统主要的开发形式就是SPA
什么是路由
安装
使用路由需要安装插件
- yarn
$ yarn add vue-router@4 vue3中使用vue-router4的版本 $yarn add vue-router@3 vue2中使用vue-router3的版本
手动在 src 目录下新建 router 文件夹 在该文件夹内创建 index.ts
使用
src/router/index.ts
// todo 1、从vue-router中结构出createRouter// 从vue-router中结构出createWebHistory表示使用history模式 首选// 从vue-router中结构出createWebHashHistory表示使用hash模式import {createRouter,createWebHistory,createWebHashHistory} from 'vue-router'// todo 2、创建路由实例并传递 `routes` 配置const router =createRouter({// history: 是用于选择路由的模式:history:createWebHistory(), // 这是使用 history 模式// routes: 路由表,用于确定一个路由对应一个组件 使得每个路由都需要映射到一个组件routes:[] // 在此处打造路由表})// todo 3、导出router实例export default router// 去main.ts激活组册
vue路由的模式:
hash 模式:#/home 兼容性强支持所有浏览器
原理:window.onhashchange = function () => {} // 监听url改变的history 模式:/home 依赖 HTML5 History API和服务器配置,需要后端支持
原理:window.onpopstate = function () => {} / history API // 监听路由改变
scr/main.ts
入口文件main.ts中引入路由实例 router , 然后在根实例中注册
import { createApp } from 'vue'import App from './App.vue'// 引入路由实例 routerimport router from './router'// 激活组册createApp(App).use(router).mount('#app')// createApp(App).mount('#app')
打造路由表(定义一些路由)
routes:[{path,component,meta,redirect,alias,children,beforeEnter}]
path 路由路径 /homecomponent 路由渲染的组件meta 元数据 用于携带数据 比如做类似权限的功能redirect 重定向alias 别名children 子路由表() /home/hotbeforeEnter 路由独享守卫,用于判断你是否有权限进入当前路由
在这里定义一些路由
const routes = [{path: "/home",// 组件 在scr/page目录用于存放组件 home/index.vue// component后面跟着的组件需要使用路由懒加载,需要的时候才加载component: () =>import(/*webpackChunkName:"home"*/ "../page/home/index.vue"),name: "home", // 命名路由,给路由起个名字,通过名字快速找到该路由alias: "family",},{path: "/about",component: () =>import(/*webpackChunkName:'about'*/ "../page/about/index.vue"),name:'about'},]
组件路由懒加载写法
component: () => import(/*webpackChunkName:"home"*/ "../page/home/index.vue")
1、( ) => import() 表示vue的异步组件 需要的时候才加载,放入异步队列 2、/webpackChunkName/ webpack的代码分割功能 当一个组件很大的时候比较消化时间,将组件进行分割展示,给一个名字实现组件合并
捕获所有路由或 404 Not found 路由 (错误路由匹配)
注意⚠️:vue规定错误路由匹配必须放在最下面,它必须将上面的路由全找一遍,找不到才用当前这个。
常规参数只匹配 url 片段之间的字符,用 / 分隔。如果我们想匹配任意路径,我们可以使用自定义的 路径参数 正则表达式,在 路径参数 后面的括号中加入 正则表达式 :
const roust = [{path: "/:pathMatch(.*)*",component: () => ,name: "NotFound"}]
404时界面公共内容控制
使用useRoute中的
<script lang="ts">import { defineComponent,reactive,watch ,toRefs} from 'vue'import {useRoute} from 'vue-router' // vue-router中结构出useRouteexport default defineComponent({setup() {const state=reactive({navFlag:true})const route=useRoute()watch(()=>route.path ,()=>{ // 监听路径的变化if(route.matched[0].path=='/:pathMatch(.*)*'){ // 匹配路径相等时触发state.navFlag=false}else{state.navFlag=true}})return {...toRefs(state)}},})</script>
App.vue
利用内置内置组件实现路由切换,成为声明式页面跳转 还有一种命令式跳转会在动态路由中提及
<template><div><h1>SPA</h1><!-- 导航区域 --><!-- router-link是vue-router提供的内置组件,用于声明式跳转页面 --><!-- 通过传递'to'来指定连接 --><!-- 通过'active-class="className"来指定选择时的样式' --><div v-if="navFlag"><ul class="app-nav-list"><li>// active-class="className" 激活导航样式<router-link active-class="active" to="/home_1">Home</router-link></li><li><router-link active-class="active" to="/about">about</router-link></li></ul></div><!-- 路由展示区域 (路由出口) --><!-- 路由匹配到到组件将渲染在这里 --><div class="app-router-content"><!-- router-view也是vue-router提供的内置组件,用于渲染路由对应的组件 --><router-view></router-view></div></div></template><script>...同上</script><style lang="stylus">.app-nav-listwidth 500pxdisplay flexjustify-content space-evenly.app-router-contentmargin-left 80px.activebackground redcolor white</style>
router-link
请注意,我们没有使用常规 a 标签,而是使用一个自定义组件 router-link 来创建链接。这使得Vue Router可以在不重新加载页面到情况下更新URL,处理URL到生成以及编码。
router-view
router-view 将显示与url对应的组件。你可以把它放在任何地方,以适应你的布局
Vue2 中 vue-router3 的使用
安装
$ yarn add vue-router@3
简单的使用
// 该文件用于创建整个应用的路由器// 引入Vueimport Vue from 'vue';// 引入vueRouterimport VueRouter from 'vue-router';// 使用VueRouter插件Vue.use(VueRouter);// 引入路由组件import Home from '../components/Router-home';import About from '../components/Router-about';// 创建一个路由表const routes = [{ path: '/home', component: Home },{ path: '/about', component: About },]// 创建并导出一个路由器export default new VueRouter({routes, // 是routes 不是 routers!!!!写错了不展示 也不报错 这个很坑的});
import Vue from 'vue'import App from './App.vue'// 引入路由器import router from './router';console.log(router);Vue.config.productionTip = false;new Vue({render: h => h(App),// vue配置项中添加 router 项router, // 此时url从原来的 http://localhost:8080/ 变为 http://localhost:8080/#/}).$mount('#app')
<template><div><h1>Vue Router Demo</h1><div><!-- vue中借助router-link标签实现路由的切换 --><router-link active-class="pickOn" to="/home">home</router-link> <router-link active-class="pickOn" to="/about">about</router-link></div><div><!-- 指定组件的呈现位置 --><router-view></router-view></div></div></template>
