实现一个简单的vue-router
所有项目的源代码都放在我的github上,欢迎大家start: https://github.com/Jasonwang911/my-vue-router
首先来看下vue-router的使用:
import Vue from 'vue';
import VueTouter from 'vue-router';
// VueRouter 是一个类,用来new 一个实例 // 注册vue-router
Vue.use(VueRouter); new VueRouter({
mode: 'hash', // hash 或者是 history
routes: [
{path: '/home', component: Home },
]
})
vue项目的入口文件中:
import Vue from "vue";
import App from "./App.vue";
// 引入配置好的router
import router from "@/router"; Vue.config.productionTip = false; new Vue({
//将路由注入根组件
router,
render: h => h(App)
}).$mount("#app");
同时视图文件展示在全局组件 router-view 上,并使用全局组件 router-link 进行跳转 , 并且在所有组件上都会有一个 $route 的属性集和 一个 $router 的方法集
<router-view></router-view> // 用来显示路由组件的视图组件,需要注册 Vue.use(VueRouter);
vue-router还区分两种路由模式 mode: hash模式和history模式
<router-link to="/home"></router-link> // 链接全局组件,包括一些属性 eg: to
this.$route 属性集
this.$router 方法集
1.hash模式的基本原理是在页面加载完和hash发生变化的时候获取 location.hash, 代码放在我的github上: https://github.com/Jasonwang911/my-vue-router/blob/master/static/hash.html
<body>
<!-- hash -->
<a href="#/home">首页</a>
<a href="#/about">关于我们</a>
<div id="html"></div> <script>
window.addEventListener('load', () => {
html.innerHTML = location.hash.slice(1);
})
window.addEventListener('hashchange', () => {
html.innerHTML = location.hash.slice(1);
})
</script>
2.history的基本原来是使用浏览器的 history API 演示代码放在我的github上: https://github.com/Jasonwang911/my-vue-router/blob/master/static/history.html
<body>
<a onclick="go('/home')">首页</a>
<a onclick="go('/about')">关于</a>
<div id="html"></div> <script>
function go(pathname) {
// 传入的数据 标题null 真正的路径 --- 页面不会刷新,后退按钮有问题
history.pushState({}, pathname, pathname);
html.innerHTML = pathname;
}
// 浏览器的后退按钮
window.addEventListener('popstate', () => {
go(location.pathname);
})
</script>
简单介绍一下注册插件 vue.use 这个方法: vue要求在插件上添加一个 install 的方法,这个方法接收两个参数,第一个参数是vue, 第二个参数是options, options用来给插件传值
import Vue from 'vue';
import VueRouter from '@/router/vue-router.js'; // 注册组件
Vue.use(VueRouter, {name: 'jason', age: 18}); // VueRouter 的类 (/router/vue-router.js)
class VueRouter { } // 使用vue.use 就会调用 install 方法, 方法上有一个参数是vue实例
VueRouter.install = function(Vue, options) {
console.log(Vue, options);
} export default VueRouter;
根据上面的思路来简单实现一下vue-router(只实现了部分功能和一层组件,如果需要实现子路由请自行递归):
import Vue from 'vue';
// 路由的history属性类
class HistoryRoute {
constructor() {
this.current = null;
}
} // VueRouter 的类
class VueRouter {
// options 中包含 mode 和 routes
constructor(options) {
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
// 把routes改成 路径:组件 的键值对对象,方便拿到路径直接渲染组件
this.routesMap = this.createMap(this.routes);
console.log('收敛后的路由表===>',this.routesMap);
// 路由中history属性存放当前路径 创建一个history类,方便扩展属性 {currnet: null}
this.history = new HistoryRoute;
// 初始化操作
this.init();
} init() {
console.log('执行了初始化的操作')
// 判断路由模式
if(this.mode === 'hash') {
// 先判断用户打开时有没有hash,没有就跳转到 #/
location.hash ? '' : location.hash = '/';
// 页面加载完成当前路径写入this.history
window.addEventListener('load', () => {
this.history.current = location.hash.slice(1);
});
// 监听 hash 变化并把当前路径存入 this.history
window.addEventListener('hashchange', () => {
this.history.current = location.hash.slice(1);
});
}else if(this.mode === 'history'){
// 判断用户打开页面的 pathname
location.pathname ? '' : location.pathname = '/';
// 页面加载完成当前路径写入this.history
window.addEventListener('load', () => {
this.history.current = location.pathname;
});
// 监听 history 变化并把当前路径存入 this.history
window.addEventListener('popstate', () => {
this.history.current = location.pathname;
});
}else {
throw new Error(`vue-router mode error, can no font router mode: ${this.mode}`);
}
} // 收敛路由表 this.routes
createMap(routes) {
return routes.reduce((prev, next, index, arr) => {
prev[next.path] = next.component;
return prev;
}, {});
}
} // 使用vue.use 就会调用 install 方法, 方法上有一个参数是vue实例
VueRouter.install = function(Vue) {
// 混合到每个组件中路由属性和路由方法 每个组件都有 this.$router / this.$toute this是当前的组件 组件中所有属性都在 this.$options上
Vue.mixin({
beforeCreate () {
// this.$router 是 vue-router 的实例, 即 VueRouter, 在 main.js中实例化vue的时候传入的 vue-router 实例,需要在所有组件中拿到这个路由实例
// vue 组件是从上到下渲染的
if(this.$options && this.$options.router) {
// 根组件
this._root = this;
this._router = this.$options.router;
// vue.util.defineReactive 是vue的一个核心库, 接收三个参数, 监听谁,第二个参数是一个别名,第三个参数如果是对象会深度监听,给对象中的每个属性加上set方法
// hostoryzhong de current发生变化会令视图发生变化
Vue.util.defineReactive(this, 'xxx' , this._router.history );
}else {
this._root = this.$parent._root;
}
Object.defineProperty(this, '$router', {
get() {
return this._root._router;
}
});
// this.$route 是路由实例的属性
Object.defineProperty(this, '$route', {
get() {
return {
current: this._root.history.current
}
}
});
}
});
// 注册全局组件
Vue.component('router-link', {
props: {
to: {
type: String,
default: ''
},
tag: String
},
methods: {
// <tag on-click={this.handleClick.bind(this)}></tag>
handleClick() { }
},
// h 表示 createElement
render(h) {
let mode = this._self._root._router.mode;
let tag = this.tag;
// return h('a', {}, '首页');
return <a href={mode === 'hash' ? `#${this.to}` : this.to}>{this.$slots.default}</a>
}
});
// 根据当前的状态 history.current 匹配 收敛后的路由表
Vue.component('router-view', {
// this 是 proxy
// h 表示 createElement
render(h) {
// console.log(this); 先注册组件然后才页面加载完成执行 onload , 需要 currnet 变化 视图更新 --- vue 双向绑定 Object.defineProperty
console.log('====>', this._root)
let current = this._root._router.history.current;
let routeMap = this._self._root._router.routesMap;
console.log(current)
return h(routeMap[current]);
}
});
} export default VueRouter;
所有项目的源代码都放在我的github上,欢迎大家start: https://github.com/Jasonwang911/my-vue-router
实现一个简单的vue-router的更多相关文章
- 搭建Vue.js环境,建立一个简单的Vue项目
基于vue-cli快速构建 Vue是近年来比较火的一个前端框架,所以搭建Vue.js环境,要装webpack,vue-cli,Vue 安装webpack命令如下 $ cnpm install webp ...
- 手把手教你从零写一个简单的 VUE
本系列是一个教程,下面贴下目录~1.手把手教你从零写一个简单的 VUE2.手把手教你从零写一个简单的 VUE--模板篇 今天给大家带来的是实现一个简单的类似 VUE 一样的前端框架,VUE 框架现在应 ...
- 一个简单的 vue.js 实践教程
https://segmentfault.com/a/1190000006776243?utm_source=tuicool&utm_medium=referral 感觉需要改善的地方有: ( ...
- 实现一个简单的Vue插件
我们先看官方文档对插件的描述 插件通常会为 Vue 添加全局功能.插件的范围没有限制--一般有下面几种: 1.添加全局方法或者属性,如: vue-custom-element 2.添加全局资源:指令/ ...
- mvvm实现一个简单的vue
vue,基于mvvm模式下的一个前端框架 mvvm模式下简单的实现数据代理,数据劫持 1.是用Object.defineProperty 实现数据代理 2.使用发布订阅者模式,配合 Object.de ...
- 60行代码实现一个迷你版Vue Router
这是一个超级精简版的VueRouter,实现hash模式下,hash改变组件切换的功能,原理就是利用了 Vue.js 的响应式机制触发router-view组件的重新渲染. 代码 https://gi ...
- 一个简单的Vue.js组件开发示例
//创建属于自己的vue组件库 (function(Vue, undefined) { Vue.component("my-component", { template: '< ...
- 记录一个简单的vue页面实现
<template> <div class="userView"> <!-- 页眉颜色统一 --> <div class="bu ...
- Vue-cli安装步骤,搭建一个完整的 Vue 项目
安装node环境下载 node.js 官网地址:https://nodejs.org/en/ 下载完成后打开然后一路next安装完成后打开 dos 窗口输入命令:node -v 回车会输出node的版 ...
- VSCode配置简单的vue项目
VSCode配置简单的vue项目 https://www.cnblogs.com/wnxyz8023/p/9989447.html 由于最近要使用的项目框架为前后端分离的,采用的是vue.js+web ...
随机推荐
- 注解@ResponseBody的作用
@ResponseBody通常是放在方法上,主要是在前端页面异步请求的时候,返回数据使用.直白点说就是加上这个注解之后,return的数据不会解析成返回跳转路径,而是会默认放在 response b ...
- 通过flask的request对象获取url
测试了一下:通过发送 GET 到 http://127.0.0.1:5000/test/a?x=1, 后台输出为(官网说明): 1 request.path: /test/a 2 request.ho ...
- delphi 中record 的类操作符重载简介
今天简单介绍一下 delphi 中record 的类操作符重载使用,就是如何 实现 record 之间的简单操作. 关于类操作符重载 ,大家可以看官方的文档. Delphi allows certai ...
- ubuntu下签名命令
Platform: RockchipOS: Android 6.0Kernel: 3.10.92 拷贝签名文件/signapk.jar和apk到同一目录下. 签名文件:rk3288/build/tar ...
- 【repost】JavaScript 运行机制详解:再谈Event Loop
一年前,我写了一篇<什么是 Event Loop?>,谈了我对Event Loop的理解. 上个月,我偶然看到了Philip Roberts的演讲<Help, I'm stuck i ...
- Thinking in Java Chapter 13
From Thinking in Java 4th Edition String对象是不可变的.String类中每一个看起来会修改String值的方法,实际上都是创建了一个全新的String对象,以包 ...
- 实现一个简单的C++协程库
之前看协程相关的东西时,曾一念而过想着怎么自己来实现一个给 C++ 用,但在保存现场恢复现场之类的细节上被自己的想法吓住,也没有深入去研究,后面一丢开就忘了.近来微博上看人在讨论怎么实现一个 user ...
- Python selenium + Firefox启动浏览器
Python selenium 的运用 from selenium import webdriver # from selenium.webdriver.firefox.firefox_profile ...
- JavaSE核心之一:Date类、Calendar类、Math类、枚举;
1.Date类 1) java.util.Date类用于封装日期及时间信息,一般仅用它显示某个日期,不对他作任何操作处理,作处理用Calendar类,计算方便. 2) Date 类本质上拥有一个lon ...
- Turtle库学习笔记
一.Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,从而在它 ...