前言路由是用来跟后端服务器进行交互的一种方式,通过不同的路径来请求不同的资源,请求不同的页面是路由的其中一项功能。VueRouter则是Vue的路由管理器
VueRouter本质
根据"不同的hash值"或者"不同的路径地址", 将不同的内容渲染到router-view
中 所以实现VueRouter
的核心关键点就在于如何监听'hash'或'路径'的变化, 再将不同的内容写到router-view
中
popstate监听历史记录点
vue-router 的 history 模式是使用浏览器的 history state
来实现的,history state
是通过 History 对象来操作的。 popstate
事件是通过 window.addEventListener('popstate')
进行注册的。但触发条件需要满足下面两点:
- 点击浏览器的【前进】【后退】按钮,或者调用
history
对象的back
、forward
、go
方法 - 之前调用过
history
对象的replaceState
或pushState
方法
<a onclick="go('/home')">首页</a>
<a onclick="go('/about')">关于</a>
<div id="html"></div>
function go(path) {
// console.log(path);
history.pushState(null, null, path);
document.querySelector('#html').innerHTML = path;
}
window.addEventListener('popstate', ()=>{
console.log('点击了前进或者后退', location.pathname);
document.querySelector('#html').innerHTML = location.pathname;
})
hashchange 事件
- 当URL的片段标识符更改时,将触发
hashchange
事件(跟在#符号后面的URL部分,包括#符号) hashchange
事件触发时,事件对象会有hash
改变前的URL(oldURL)
和hash
改变后的URL(newURL)两个属性
window.addEventListener('hashchange', ()=>{
// console.log('当前的hash值发生了变化');
let currentHash = location.hash.slice(1);
document.querySelector('#html').innerHTML = currentHash;
})
VueRouter结构
src-> router-> index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
提取路由信息
创建一个新的js文件(myVue-Router.js),搭建基本的路由信息框架
class VueRouter {
constructor(options){
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
this.routesMap = this.createRoutesMap();
}
createRoutesMap(){
return this.routes.reduce((map, route)=>{
map[route.path] = route.component;
return map;
}, {})
}
}
VueRouter.install = (Vue, options)=>{
}
export default VueRouter;
初始化路由信息
class VueRouteInfo {
constructor(){
this.currentPath = null;
}
}
class VueRouter {
constructor(options){
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
// 提取路由信息
this.routesMap = this.createRoutesMap();
// 记录当前路由
this.routeInfo = new VueRouteInfo();
// 初始化默认的路由信息
this.initDefault();
}
initDefault(){
if(this.mode === 'hash'){
// 1.判断打开的界面有没有hash, 如果没有就跳转到#/
if(!location.hash){
location.hash = '/';
}
// 2.加载完成之后和hash发生变化之后都需要保存当前的地址
window.addEventListener('load', ()=>{
this.routeInfo.currentPath = location.hash.slice(1);
});
window.addEventListener('hashchange', ()=>{
this.routeInfo.currentPath = location.hash.slice(1);
console.log(this.routeInfo);
});
}else{
// 1.判断打开的界面有没有路径, 如果没有就跳转到/
if(!location.pathname){
location.pathname = '/';
}
// 2.加载完成之后和history发生变化之后都需要保存当前的地址
window.addEventListener('load', ()=>{
this.routeInfo.currentPath = location.pathname;
});
window.addEventListener('popstate', ()=>{
this.routeInfo.currentPath = location.pathname;
console.log(this.routeInfo);
});
}
}
createRoutesMap(){
return this.routes.reduce((map, route)=>{
map[route.path] = route.component;
// { /home: Home }
return map;
}, {})
}
}
VueRouter.install = (Vue, options)=>{
}
export default VueRouter;
注入全局属性
VueRouter.install = (vm, options)=>{
vm.mixin({
beforeCreate(){
if(this.$options && this.$options.router){
this.$router = this.$options.router;
this.$route = this.$router.routeInfo;
// 实时监听路由变化
vm.util.defineReactive(this, 'xxx', this.$router);
}else{
this.$router = this.$parent.$router;
this.$route = this.$router.routeInfo;
}
}
});
}
自定义RouterLink
vm.component('router-link', {
props: {
to: String
},
render(){
// console.log(this._self.$router.mode);
let path = this.to;
if(this._self.$router.mode === 'hash'){
path = '#' + path;
}
return <a href={path}>{this.$slots.default}</a>
}
});
自定义RouterView
vm.component('router-view', {
render(h){
let routesMap = this._self.$router.routesMap;
let currentPath = this._self.$route.currentPath;
let currentComponent = routesMap[currentPath];
return h(currentComponent);
}
});
完整示例
App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/home">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view></router-view>
</div>
</template>
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
src-> router-> index.js 看上面的VueRouter结构
src-> router-> myVue-Router.js
class VueRouteInfo {
constructor(){
this.currentPath = null;
}
}
class VueRouter{
constructor(options){
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
// 1、提取路由信息
this.routesMap = this.createRoutesMap();
this.routeInfo = new VueRouteInfo();
// 2、初始化默认的路由信息
this.initDefault();
}
createRoutesMap(){
return this.routes.reduce((map, route) =>{
// 组件作为key返回
map[route.path] = route.component;
return map;
},{})
}
initDefault(){
if (this.mode === 'hash'){
// 1) 判断打开的界面有没有hash, 如果没有就跳转到#/
if (!location.hash){
location.hash = '/'
}
// 2) 加载完成之后和hash发生变化之后都需要保存当前的地址
window.addEventListener('load', ()=>{
this.routeInfo.currentPath = location.hash.slice(1);
});
window.addEventListener('hashchange', ()=>{
this.routeInfo.currentPath = location.hash.slice(1)
})
} else {
// 1) 判断打开的界面有没有路径, 如果没有就跳转到/
if (!location.pathname){
location.pathname = '/'
}
// 2)加载完成之后和history发生变化之后都需要保存当前的地址
window.addEventListener('load', ()=>{
this.routeInfo.currentPath = location.pathname
});
window.addEventListener('popstate', ()=>{
this.routeInfo.currentPath = location.pathname;
});
}
}
}
VueRouter.install = (vm, options) =>{
// 3、全局注入属性
vm.mixin({
beforeCreate() {
if (this.$options && this.$options.router){
this.$router = this.$options.router;
this.$route = this.$router.routeInfo;
// 实时监听路由变化
vm.util.defineReactive(this, 'xxx', this.$router);
} else {
this.$router = this.$parent.$router;
this.$route = this.$router.routeInfo;
}
}
});
// 4、自定义路由组件
vm.component('router-link', {
props: {
to: String
},
render() {
let path = this.to;
if(this._self.$router.mode === 'hash'){
path = '#' + path;
}
return<a href={path}>{this.$slots.default}</a>
}
})
vm.component('router-view', {
render(h) {
let routerMap = this._self.$router.routesMap;
let currentPath = this._self.$route.currentPath;
let currentComponent = routerMap[currentPath];
return h(currentComponent)
}
})
};
export default VueRouter