vue路由器开发活动
今天和朋友们分享vue路由器开发活动相关的知识,相信大家通过本文介绍也能对vue路由使用方法有自已的收获和理解。自己轻松搞问题。
本文内容目录一览:
vue中路由的动态keepAlive
如果想让vue的所有页面都保持keepAlive的状态。只需要在app.vue的router-view外面套一层keep-alive
如果只想让某些路由保持keepAlive,只需要向keep-alive传入include(不想让某些路由keepAlive,其他的都keepAlive。则需传入exclude)
而include的数组完全可以通过函数获取。所以只需要在router.js中,在定义每个路由时说明其是keepAlive,并且在app.js中能够获取到该状态即可。这里给出的做法是定义路由时,通过meta给出状态,并将该状态的路由存入sessionStorage,在app.js中再通过sessionStorage取出来。
此时,在进入某个路由前,路由的地址已经存入了sessionStorage
app.vue中需要watch $router ,并从sessionStorage中取出,放到data里。
keepAlive的:include再返回data中刚放入的地址数组
vue跳路由的时候,页面从右向做进入的动效果,怎么实现呢?
用vue自带的transition可以实现。
transition组件可以定义自己的动画方法,也可以通过css3进行设置。具体用法可以查看官方文档。
vue 项目路由权限管理实现
项目基于 vue-element-admin 基础之上进行开发,感谢 花裤衩 以及为此项目做出贡献的大佬 [社会社会]!
路由数据由后端控制,前端调用接口返回数据;前端拿到数据处理成可使用的路由结构,然后渲染到页面。
为了能提供更多的功能,后端返回的数据结构是在原来菜单结构基础之上有所改动的。
原路由数据结构:
后端返回数据结构:
路由数据采用多级嵌套结构,基本可以满足需求。
拿到接口返回的数据之后还不能直接使用,需要经过一些处理。
在本地的开发,新增页面时,为了方便开发,获取到后端返回的数据之后用了一个方法来合并数据:
temporaryMenuArray 临时路由数组的结构需要跟后端返回的数据结构一致。
使用 setTemporaryMenu :
合并完临时的路由之后就开始进行路由的处理了。
从上面后端返回的数据结构中可以看出,已经和需要处理成的路由很像了,但还是有一些数据没有必要在专门的系统那里维护,所以需要一些其他数据的处理:
routesComponents 为一个手动维护的页面路由文件:
得到的 userCanUseRouteModules 结构如下:
上面数据中的 type 为2、3层级的 component 已经被替换成对应页面的路由模块了。
得到 userCanUseRouteModules 之后,其中 name 为 storeManagement:head 的那一层数据是供头部菜单使用的,其 children 的数据才是需要添加的路由数据:
此时的 asyncRoutes 只放了默认匹配的路由,这个是需要放在所有路由的最后的:
至此对路由的处理结束。
处理路由这一步是放在 router.beforeEach 路由全局前置守卫里的,结合原有的逻辑进行了一些判断处理。
因为路由数据是由后端数据处理得到的,只包含和挂载了当前用户能有权限访问的部分,没有权限访问的路由就没有被 router.addRoutes 添加,所以并没有在路由守卫里对每次路由的跳转都进行校验。
vue实现路由跳转的原理是什么,是调用js底层什么方法
前端路由是直接找到与地址匹配的一个组件或对象并将其渲染出来。改变浏览器地址而不向服务器发出请求有两种方式:
1. 在地址中加入#以欺骗浏览器,地址的改变是由于正在进行页内导航
2. 使用H5的window.history功能,使用URL的Hash来模拟一个完整的URL。
当打包构建应用时,Javascript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
目录结构
先来看看整体的目录结构
和流程相关的主要需要关注点的就是 components、history 目录以及 create-matcher.js、create-route-map.js、index.js、install.js。下面就从 basic 应用入口开始来分析 vue-router 的整个流程。
import Vue from 'vue'
import VueRouter from 'vue-router'
// 1. 插件
// 安装 router-view and router-link 组件
// 且给当前应用下所有的组件都注入 $router and $route 对象
Vue.use(VueRouter)
// 2. 定义各个路由下使用的组件,简称路由组件
const Home = { template: 'divhome/div' }
const Foo = { template: 'divfoo/div' }
const Bar = { template: 'divbar/div' }
// 3. 创建 VueRouter 实例 router
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
// 4. 创建 启动应用
// 一定要确认注入了 router
// 在 router-view 中将会渲染路由组件
new Vue({
router,
template: ` div id="app"
h1Basic/h1
ul
lirouter-link to="/"//router-link/li
lirouter-link to="/foo"/foo/router-link/li
lirouter-link to="/bar"/bar/router-link/li
router-link tag="li" to="/bar"/bar/router-link
/ul
router-view class="view"/router-view
/div
`
}).$mount('#app')123456789101112131415161718192021222324252627282930313233343536373839404142
作为插件
上边代码中关键的第 1 步,利用 Vue.js 提供的插件机制 .use(plugin) 来安装 VueRouter,而这个插件机制则会调用该 plugin 对象的 install 方法(当然如果该 plugin 没有该方法的话会把 plugin 自身作为函数来调用);下边来看下 vue-router 这个插件具体的实现部分。
VueRouter 对象是在 src/index.js 中暴露出来的,这个对象有一个静态的 install 方法:
/* @flow */
// 导入 install 模块
import { install } from './install'// ...import { inBrowser, supportsHistory } from './util/dom'// ...export default class VueRouter {
// ...}
// 赋值 install
VueRouter.install = install
// 自动使用插件if (inBrowser window.Vue) {
window.Vue.use(VueRouter)
}123456789101112131415161718
可以看到这是一个 Vue.js 插件的经典写法,给插件对象增加 install 方法用来安装插件具体逻辑,同时在最后判断下如果是在浏览器环境且存在 window.Vue 的话就会自动使用插件。
install 在这里是一个单独的模块,继续来看同级下的 src/install.js 的主要逻辑:
// router-view router-link 组件import View from './components/view'import Link from './components/link'// export 一个 Vue 引用export let _Vue// 安装函数export function install (Vue) {
if (install.installed) return
install.installed = true
// 赋值私有 Vue 引用
_Vue = Vue // 注入 $router $route
Object.defineProperty(Vue.prototype, '$router', {
get () { return this.$root._router }
}) Object.defineProperty(Vue.prototype, '$route', {
get () { return this.$root._route }
}) // beforeCreate mixin
Vue.mixin({
beforeCreate () { // 判断是否有 router
if (this.$options.router) { // 赋值 _router
this._router = this.$options.router // 初始化 init
this._router.init(this) // 定义响应式的 _route 对象
Vue.util.defineReactive(this, '_route', this._router.history.current)
}
}
}) // 注册组件
Vue.component('router-view', View)
Vue.component('router-link', Link)// ...}12345678910111213141516171819202122232425262728293031323334353637383940414243
这里就会有一些疑问了?
· 为啥要 export 一个 Vue 引用?
插件在打包的时候是肯定不希望把 vue 作为一个依赖包打进去的,但是呢又希望使用 Vue 对象本身的一些方法,此时就可以采用上边类似的做法,在 install 的时候把这个变量赋值 Vue ,这样就可以在其他地方使用 Vue 的一些方法而不必引入 vue 依赖包(前提是保证 install 后才会使用)。
· 通过给 Vue.prototype 定义 $router、$route 属性就可以把他们注入到所有组件中吗?
在 Vue.js 中所有的组件都是被扩展的 Vue 实例,也就意味着所有的组件都可以访问到这个实例原型上定义的属性。
beforeCreate mixin 这个在后边创建 Vue 实例的时候再细说。
实例化 VueRouter
在入口文件中,首先要实例化一个 VueRouter ,然后将其传入 Vue 实例的 options 中。现在继续来看在 src/index.js 中暴露出来的 VueRouter 类:
// ...import { createMatcher } from './create-matcher'// ...export default class VueRouter {
// ...
constructor (options: RouterOptions = {}) {
this.app = null
this.options = options
this.beforeHooks = []
this.afterHooks = []
// 创建 match 匹配函数
this.match = createMatcher(options.routes || [])
// 根据 mode 实例化具体的 History
let mode = options.mode || 'hash'
this.fallback = mode === 'history' !supportsHistory if (this.fallback) {
mode = 'hash'
} if (!inBrowser) {
mode = 'abstract'
}
this.mode = mode switch (mode) {
case 'history':
this.history = new HTML5History(this, options.base) break
case 'hash':
this.history = new HashHistory(this, options.base, this.fallback) break
case 'abstract':
this.history = new AbstractHistory(this) break
default:
assert(false, `invalid mode: ${mode}`)
}
}
// ...}123456789101112131415161718192021222324252627282930313233343536373839
里边包含了重要的一步:创建 match 匹配函数。
match 匹配函数
匹配函数是由 src/create-matcher.js 中的 createMatcher 创建的:
/* @flow */
import Regexp from 'path-to-regexp'// ...import { createRouteMap } from './create-route-map'// ...export function createMatcher (routes: ArrayRouteConfig): Matcher {
// 创建路由 map
const { pathMap, nameMap } = createRouteMap(routes)
// 匹配函数 function match (
raw: RawLocation,
currentRoute?: Route,
redirectedFrom?: Location
): Route {
// ...
} function redirect (
record: RouteRecord,
location: Location
): Route {
// ...
} function alias (
record: RouteRecord,
location: Location,
matchAs: string
): Route {
// ...
} function _createRoute (
record: ?RouteRecord,
location: Location,
redirectedFrom?: Location
): Route { if (record record.redirect) { return redirect(record, redirectedFrom || location)
} if (record record.matchAs) { return alias(record, location, record.matchAs)
} return createRoute(record, location, redirectedFrom)
}
// 返回 return match
}
// ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
具体逻辑后续再具体分析,现在只需要理解为根据传入的 routes 配置生成对应的路由 map,然后直接返回了 match 匹配函数。
继续来看 src/create-route-map.js 中的 createRouteMap 函数:
/* @flow */import { assert, warn } from './util/warn'import { cleanPath } from './util/path'// 创建路由 mapexport function createRouteMap (routes: ArrayRouteConfig): {
pathMap: DictionaryRouteRecord,
nameMap: DictionaryRouteRecord
} { // path 路由 map
const pathMap: DictionaryRouteRecord = Object.create(null) // name 路由 map
const nameMap: DictionaryRouteRecord = Object.create(null) // 遍历路由配置对象 增加 路由记录
routes.forEach(route = {
addRouteRecord(pathMap, nameMap, route)
}) return {
pathMap,
nameMap
}
}// 增加 路由记录 函数function addRouteRecord (
pathMap: DictionaryRouteRecord,
nameMap: DictionaryRouteRecord,
route: RouteConfig,
parent?: RouteRecord,
matchAs?: string
) {
// 获取 path 、name
const { path, name } = route
assert(path != null, `"path" is required in a route configuration.`) // 路由记录 对象
const record: RouteRecord = {
path: normalizePath(path, parent),
components: route.components || { default: route.component },
instances: {},
name, parent,
matchAs,
redirect: route.redirect,
beforeEnter: route.beforeEnter,
meta: route.meta || {}
} // 嵌套子路由 则递归增加 记录
if (route.children) {// ...
route.children.forEach(child = {
addRouteRecord(pathMap, nameMap, child, record)
})
} // 处理别名 alias 逻辑 增加对应的 记录
if (route.alias !== undefined) { if (Array.isArray(route.alias)) {
route.alias.forEach(alias = {
addRouteRecord(pathMap, nameMap, { path: alias }, parent, record.path)
})
} else {
addRouteRecord(pathMap, nameMap, { path: route.alias }, parent, record.path)
}
} // 更新 path map
pathMap[record.path] = record // 更新 name map
if (name) { if (!nameMap[name]) {
nameMap[name] = record
} else {
warn(false, `Duplicate named routes definition: { name: "${name}", path: "${record.path}" }`)
}
}
}function normalizePath (path: string, parent?: RouteRecord): string {
path = path.replace(/\/$/, '') if (path[0] === '/') return path if (parent == null) return path return cleanPath(`${parent.path}/${path}`)
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
可以看出主要做的事情就是根据用户路由配置对象生成普通的根据 path 来对应的路由记录以及根据 name 来对应的路由记录的 map,方便后续匹配对应。
实例化 History
这也是很重要的一步,所有的 History 类都是在 src/history/ 目录下,现在呢不需要关心具体的每种 History 的具体实现上差异,只需要知道他们都是继承自 src/history/base.js 中的 History 类的:
/* @flow */// ...import { inBrowser } from '../util/dom'import { runQueue } from '../util/async'import { START, isSameRoute } from '../util/route'// 这里从之前分析过的 install.js 中 export _Vueimport { _Vue } from '../install'export class History {// ...
constructor (router: VueRouter, base: ?string) { this.router = router this.base = normalizeBase(base) // start with a route object that stands for "nowhere"
this.current = START this.pending = null
}// ...}// 得到 base 值function normalizeBase (base: ?string): string { if (!base) { if (inBrowser) { // respect base tag
const baseEl = document.querySelector('base') base = baseEl ? baseEl.getAttribute('href') : '/'
} else { base = '/'
}
} // make sure there's the starting slash
if (base.charAt(0) !== '/') { base = '/' + base
vue路由器开发活动的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于vue路由使用方法、vue路由器开发活动的信息别忘了在本站进行查找喔。