简易剖析全过程
1、建立一个vue-router.js文档 // 申明自变量,缓存文件Vue案例目标 let Vue * 申明VueRouter类 class VueRouter { constructor(options) { this.$options = options // 建立一个路由器path和route投射 this.routeMap = {} // 当今相对路径current必须响应式-运用vue响应式完成 this.app = new Vue({ data: { current: / init() { // 关联访问器恶性事件,监视路由器恶性事件 this.bindEvents() // 分析传到的路由器配备-routes this.createRouteMap(this.$options); // 申明2个全局性部件:router-link 和 router-view this.initComponent() bindEvents() { window.addEventListener( hashchange , this.onHashChange.bind(this)) window.addEventListener( load , this.onHashChange.bind(this)) onHashChange() { // #/home this.app.current = window.location.hash.slice(1) || / createRouteMap(options) { // 解析xml,随后缓存文件 options.routes.forEach(item = { // [ /home ]: {path: /home , component: Home} this.routeMap[item.path] = item initComponent() { // 申明2个全局性部件 ponent( router-link , { props: { to: String render(h) { // 总体目标是: a href= to XXX /a return h( a , {attrs: {href: # + this.to}}, this.$slots.default) // return a href={this.to} this.$slots.default /a // hash - current - render ponent( router-view , { // 箭头符号涵数能保存this偏向,这儿偏向VueRouter案例 render: h = { const Comp = this.routeMap[this.app.current].component return h(Comp) // 把VueRouter变成软件-务必完成install VueRouter.install = function(_vue) { // 储存vue案例 Vue = _vue // 混入每日任务-混入便是拓展Vue Vue.mixin({ beforeCreate() { // 这儿的编码未来会出外面原始化的情况下被启用 // 那样完成了Vue拓展 // this偏向Vue部件案例 // 这儿只期待根部件实行一次 if (this.$options.router) { Vue.prototype.$router = this.$options.router // 原始化 this.$options.router.init() export default VueRouter 2、建立main.js import Vue from vue import App from ./App.vue import VueRouter from ./vue-router //以软件的方式,应用VueRouter Vue.use(VueRouter); //路由器配备信息内容,能够由外部文档引进,在此立即写是以便便捷演试 const Home = { template: div home /div } const About = { template: div about /div } const routes = [ { path: / , component: Home }, { path: /about , component: About } //原始化并与 Vue 案例关系 const router = new VueRouter({routes}); new Vue({ router, render: h = h(App), }).$mount( #root 3、建立App.vue-用以检测 template div h1 @click= goBack App Test /h1 router-link to= / Home /router-link router-link to= /bar About /router-link router-view /router-view /div /template script export default { methods: { goBack() { console.log(this.$router); window.history.length 1 ? this.$router.go(-1) : this.$router.push( / ) /script style lang= less scoped /style(责任编辑:admin) |