学习笔记
原型
import Vue from 'vue'
import VueRouter from './routers.js'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
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({
routes
})
export default router
模拟实现vue-router
//模拟Vue-router
//1.导入Vue.use
//2.创建实列
//3.添加配置项到new Vue()中
//4.路由的跳转 router-link
//5.录用的出口 router-view
//hash导航
let Vue;
import {createHashHistory} from './history.js';
class VueRouter {
constructor(options) {
this.history = createHashHistory();
this.$options = options;
//把this.current变成响应式数据
//数据一旦发生变化 router-view能够重新执行 //基于hash路由
let initial = window.location.hash.slice(1) || "/";
Vue.util.defineReactive(this, "current", initial);
//监听hash值是否发生变化
window.addEventListener("hashchange", () => {
this.current = window.location.hash.slice(1) || "/";
console.log(this.current);
})
}
/**
* 实现this.$router.push 跳转 (字符串的)
* @param {Object} RouterObj 接收router路由对象
*/
push(RouterObj) {
this.history.push(RouterObj);
}
/**
* 实现路由的单个添加
* 这里应该有判断 判断是否为重复路由 不能重复name字段 path字段
* @param {Object} SingleRoute
*/
addRoute(SingleRoute) {
this.$options.routes.push(SingleRoute);
}
}
// 1).实现并声明2个全局注册的组件,分别是router-link,router-view
// 2).实现this.$router.push()
VueRouter.install = (_Vue) => {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
//每次组件加载都会被调用
if (this.$options.router) {
Vue.prototype.$router = this.$options.router;
}
}
})
//实现2个组件
//router-link 实际就是A标签
Vue.component("router-link", {
props: {
to: {
type: String,
required: true,
}
},
render(h) {
return h("a", {
attrs: {
href: `#${this.to}`,
}
},
this.$slots.default
);
}
});
Vue.component("router-view", {
render(h) {
var component = null;
const current = this.$router.current;
let route = this.$router.$options.routes.find((router) => { /*找到相对应的路由*/
return router.path == current;
})
if (route) {
component = route.component;
}
//获取当前路由对应的组件并将他渲染出来
return h(component);
}
});
}
export default VueRouter
跳转调用
this.$router.push({path: '/index', query: {selected: "2"}})
addRoute添加
routerList: {
path: '/index',
name: 'index',
component: () => import( /* webpackChunkName: "about" */ '../views/index.vue')
},
this.$router.addRoute(this.routerList);
vue-route 笔记