目标: 主要实现router的一些基础功能,router-link、router-view
- 创建router文件夹
- 创建index.js文件
import Vue from "vue";
import VueRouter from "./kvue-router";
// 应用路由插件
Vue.use(VueRouter);
let routes = [
{
path: "/home",
name: "home",
meta: {
title: "首页",
},
component: () => import(/* webpackChunkName: "首页" */ "../views/home"),
},
{
path: "/about",
name: "about",
meta: {
title: "关于",
},
component: () => import(/* webpackChunkName: "关于" */ "../views/about"),
},
];
// 创建实例
const router = new VueRouter({
mode: "history",
routes,
scrollBehavior(to, from, savedPosition) {
// return 期望滚动到哪个的位置
return {
x: 0,
y: 0,
};
},
});
export default router;
- 创建vue-router文件
import Link from './router-link'
let Vue;
class VueRouter {
constructor(options) {
this.$options = options
// 当前路由
// this.current = '/'
// 把current变成响应式
Vue.util.defineReactive(this,'current', '/')
// 当前路由
let initUrl = window.location.hash.slice(1) || '/'
Vue.util.defineReactive(this,'current', initUrl)
window.addEventListener('hashchange', this.onHashchange.bind(this))
window.addEventListener('load', this.onHashchange.bind(this))
// 路由表
this.routeMap = {}
options.routes.forEach(route => {
this.routeMap[route.path] = route
})
}
onHashchange() {
this.current = window.location.hash.slice(1)
},
}
// 1. VueRouter变成插件形式
VueRouter.install = function(_Vue) {
Vue = _Vue
// 使用混入使$router挂载在全局
Vue.mixin({
beforeCreate() {
if(this.$options.router) {
Vue.prototype.$router = this.$options.router
}
},
})
// 2. 实现router-link router-view
Vue.component('router-link', Link)
}
- 创建router-link 文件
// router-link <router-link to='xxx'> xx </router-link> <a href="#xxx">xxx</a>
export default {
props: {
to: {
type: String,
default: ''
}
},
render(h) {
// h(标签名, data, 子元素) this.$slots.default 插槽
return h('a',{attrs:{href: '#' + this.to}}, this.$slots.default)
}
}
- 创建router-view文件
export default {
render(h) {
let component = null
// routeMap 路由表 current当前路由
let {routeMap, current} = this.$router
component = routeMap[current].component || null
return h(component)
}
}