实现一个简单的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 ...
随机推荐
- SpringBoot集成redis,使用@Cachexxxx
一.引入相关依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId& ...
- 【linux轻松学】centos6.5上搭建svn服务器
今天花了一下午,把svn环境搭好了,写篇文章分享…… 1.安装 先查看是否已经安装,如果有旧版,先删除再安装. 查看rpm -qa subversion 删除yum remove subversion ...
- (21)The history of human emotions
https://www.ted.com/talks/tiffany_watt_smith_the_history_of_human_emotions/transcript00:12I would li ...
- Django基础—1
一. Django的安装1. 查看已安装的Django的版本 进入到终端以及Python的交互模式 python3/ ipython32. 交互模式中输入import django ...
- Chapter6 胞内信号网络
一.一条从细胞表面到细胞核的通路 二.Ras蛋白处于复杂信号级联的中心位置 胞外信号→酪氨酸激酶受体→Shc→Grb→Sos→Ras 三.酪氨酸的磷酸化控制着许多胞内信号蛋白的定位与活动 Src蛋白的 ...
- Number of subarrays having sum exactly equal to k(explanation for 437. Path Sum III of leetcode)
https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/ 讲解的详细 看这道题是为了解决https://leetcode. ...
- SELECT版FTP
功能: 1.使用SELECT或SELECTORS模块实现并发简单版FTP 2.允许多用户并发上传下载文件环境: python 3.5特性: select 实现并发效果运行: get 文件名 #从服务器 ...
- Navicat for MYSQL 断网时本地连接无法打开,2005错误
Navicat for MYSQL 断网时本地连接无法打开,2005错误 NO1 提示下图: NO2 解决方法: (1)选中本地连接,右键 连接属性 (2) 将 主机名或IP地址 这一栏改为 127. ...
- 再谈控制 cxGrid 的行列颜色
1. [转]CxGrid 改变某行或单元格的颜色 (2016-01-19 09:37:19) 转载▼ 标签: it delphi 分类: Delphi 一个表(T)的结构结构如下. ID Test 1 ...
- Docker集群管理工具 - Kubernetes 部署记录 (运维小结)
一. Kubernetes 介绍 Kubernetes是一个全新的基于容器技术的分布式架构领先方案, 它是Google在2014年6月开源的一个容器集群管理系统,使用Go语言开发,Kubernete ...