(精华)2020年7月19日 vue vue-router(手写版)
发布日期:2021-06-29 15:08:02 浏览次数:3 分类:技术文章

本文共 3571 字,大约阅读时间需要 11 分钟。

import Vue from 'vue'// import VueRouter from 'vue-router'import VueRouter from '../MYRouter/index.js'Vue.use(VueRouter)// 执行install方法const routes = [  {
path:'/', redirect:'/goods' }, {
path: '/goods', name: 'goods', component: () => import('../views/goods.vue') }, {
path: '/ratings', name: 'ratings', component: () => import('../views/ratings.vue') }, {
path: '/seller', name: 'seller', component: () => import('../views/seller.vue') },]//new执行构造函数const router = new VueRouter({
routes, linkActiveClass:'active'})export default router

自定义插件MYRouter的内部写法

//我们写插件的地方let Vue ;class MYRouter {
static install(_Vue) {
//use执行的函数 Vue = _Vue; Vue.mixin({
beforeCreate(){
// const options = this.$options; //this -- vue实例化对象 Vue.prototype.$rmrouter = '我是路由!' if(this.$options.router){
//this.$options.router 在vue实例化的时候被注入的router对象 this._router = this.$options.router Vue.util.defineReactive(this._router, 'current', '/') ; //方式二 //这个是把_route加入数据监控,所以你可以watch到_route this.$options.router.init(); } } }) } constructor(options){
this.$options = options; this.routerMap = {
}; // this.currentPath = ''; //当前的path // 路由 -- 组件 // test1 --- test1.vue // //方式一: // this.app = new Vue({
// data(){
// return {
// //当前的路由 // current:'/' // } // } // }); } init(){
console.log('ppp'); //1. 监听hash的变化 this.initEvents(); //2. 处理路由routerMap this.createRouterMap(); //3 . 初始化组件 , router-link, router-view this.initComponent(); //4.路由守卫 } //1. 监听hash的变化 initEvents(){
window.addEventListener('hashchange',this.onHashChange.bind(this),false) window.addEventListener('load',this.onHashChange.bind(this),false) } //2. 处理路由routerMap createRouterMap(){
// this.routerMap = {
// '/goods':'component', // '/goods1':'component1', // } this.$options.routes.forEach((item)=>{
this.routerMap[item.path] = item; }) } onHashChange(e){
console.log('我监听到路由变化了'); //获取hash let hash = location.hash.slice(1) || '/'; this.current = hash; //方式一 } //3 . 初始化组件 , router-link, router-view initComponent(){
Vue.component('router-link',{
// props:['to'], props:{
to:String }, render:function(h){
// h-- createElemnt // 3个参数 // dom节点名 // 属性 // 子元素 return h('a',{
attrs:{
href:'#'+this.to } },[this.$slots.default]) } }); Vue.component('router-view',{
render:h=>{
console.log('ppp'); // console.log(this.app.current); //方式一 //this vuerouter实例化构造函数的对象 let component = this.routerMap[this.current].component; return h(component); } }) }}export default MYRouter;

转载地址:https://codeboy.blog.csdn.net/article/details/107440503 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:(精华)2020年7月19日 vue 手写vue底层源码
下一篇:(精华)2020年7月19日 vue vuex的使用和vuex辅助函数的使用

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月16日 07时05分38秒