plugins/vue-router.js文件中
// 1.创建一个VueRouter类
import { h } from "vue";
let Vue;
class VueRouter {
constructor(options) {
this.$options = options;
// this.current = location.hash.slice(1) || ''
// 定义一个响应式的current属性
// console.log(location.hash);
Vue.util.defineReactive(this, 'current', location.hash.slice(1) || '')
// 监听hash值的变化
window.addEventListener('hashchange', () => {
this.current = location.hash.slice(1)
})
this.routesMap = {}
// 将routes中的path和component做一个映射
this.$options.routes.forEach(item => {
this.routesMap[item.path] = item.component
})
}
}
// 2.只要是vue的插件,都要实现一个install方法
// install方法第一个参数:Vue构造函数,第二个参数是可选的,调用use方法时传递的第二个参数
VueRouter.install = function(_Vue, options) {
Vue = _Vue;
// 利用vue的混入--->mixin
// 利用混入,将挂载router实例的这段代码延迟到vue实例创建完毕之后执行
Vue.mixin({
beforeCreate() {
// 判断当前属性上是否具有router属性,避免每一个组件都执行一遍
if(this.$options.router) {
Vue.prototype.$router = this.$options.router
}
}
})
// 3.注册两个全局组件router-link 和 router-view
// router-link组件
Vue.component('router-link', {
render(h) {
return h('a', { attrs: { href: '#' + this.to } }, this.$slots.default)
}
})
// router-view组件
Vue.component('router-view', {
render() {
const path = this.$router.current;
const component = this.$router.routesMap[path];
return h(component)
}
})
}
export default VueRouter;
router/index.js 文件
import Vue from 'vue'
import VueRouter from '../plugins/vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
// 前端路由:url 和 组件的对应关系
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
}
]
const router = new VueRouter({
// mode: 'history', vue-router@3
routes
})
export default router