vue-router的简易实现

更新日期: 2019-12-29阅读: 1.8k标签: 路由

现在很多项目的前端都是用vue单页面实现的,而单页面中最重要的一个环节就是路由,今天来实现一个简易版本的vue-router。


路由

先来看下路由的工作流程

后端路由

  1. 输入url
  2. 请求发送到服务器,服务器解析请求的路径
  3. 拿到相应数据-返回给前端

前端路由

  1. 输入url
  2. js解析地址,找到对应地址的页面
  3. 执行页面生成的js和css
  4. 渲染页面

了解了路由的工作流程之后,再来看下vue-router工作流程。

  1. url改变,触发监听事件
  2. 改变vue-router的current变量(new Router中的current变量)
  3. 监视current变量的监视者
  4. 获取新的组件,render新组件

url改变,这就涉及了两种模式,hash和history。
hash的特点

  • #后的就是hash的内容,只会给浏览器,不会给服务器
  • 可以通过location.hash获取
  • 可以通过onhashchange监听hash的改变

history的特点

  • history即正常的路径
  • 可以通过location.pathname获取
  • 可以通过onpopstate见监听history变化

看下router.js中的内容,实例化的时候会传mode和routers等其他参数

import hello from './hello.vue';
new Router({
    mode:'history',
    routers:[{
      path:'/',
      name: 'hello',
      component: hello
    }]
})


vue插件

看下vue插件的用法
1.插件都是用过Vue.use方法注册的,下面来看下一段代码

// 声明一个普通的对象test
var test = {
    b: 1
}
// 写了一个定时器,2秒后改变了test的b属性的值
setTimeout(function(){
    test.b = 111;
},2000)
// 声明了一个函数a
function a(){
    console.log(1)
}
// 给a赋了一个install属性方法
a.install = function(vue){
    // 对test对象的b属性进行双向绑定
    vue.util.definereactive(test,'b')
    // 全局混入
    vue.mixin({
      beforeCreate(){
         this.test = test;
      }
    })
}
// 注册插件a
Vue.use(a);

<div>{{test.b}}</div>

运行这段代码,结果是会在页面上显示1,过了2秒会变成111,从这个demo中我们可以看出插件是可以将外面定义的变量实现双向绑定的。


实现

接下来实现了一个简易的路由,看下代码

class HistoryRoute{
    constructor(){
      this.current = null;
    }
}

class vueRouter({
    constructor(opt){
       // 路由模式
       this.mode = opt.mode || 'hash';
       // 路由配置项
       this.routes = opt.routes || [];
       this.history = new HistoryRoute;
       // 将路由配置项由数组形式转成键值对
       this.routesMap = this.createMap(this.routes);
       // 初始化,获取、监听路由
       this.init()
    }
    init(){
       if(this.mode === 'hash'){
         location.hash ? "" : location.hash="/";
         window.addEventListener('load',()=>{
            this.history.current = location.hash.splice(1);
         });
         window.addEventListener('hashchange',()=>{
             this.history.current = location.hash.splice(1)
         })
       }else {
         location.pathname ? "" : location.pathname="/";
         window.addEventListener('load',()=>{
            this.history.current = location.pathname;
         });
         window.addEventListener('popstate',()=>{
             this.history.current = location.pathname
         })
       }
    }
    createMap(routes){
      return routes.reduce((memo,current)=>{
        memo[current.path] = current.component;
        return memo;
      },{})
    }
})
vueRouter.install = vue=>{
    vue.mixin({
      beforeCreate(){
        if(this.$options && this.$options.router){
          this._root = this;
          this._router = this.$options.router;
        }
        // 对current变量进行双向绑定
        vue.util.defineReactive(this,'current', this._router.history)
      }else{
        //嵌套路由
        this._root = this.$parent._root;
      }
      // 定义this.$router的get方法,防止修改属性
      Object.defineProperty(this,'$router',{
         get(){
           return this._root._router;
         }
      })
    })
    // 注册一个router-view的组件,渲染路由组件
    vue.component('router-view',{
      render(h){
        let current = this._self._root._router.history.current;
        let routesMap = this._self._root._router.routesMap;
        return h(routesMap(current));
      }
    })
}
export default vueRouter;

链接: https://www.fly63.com/article/detial/8004

vue路由history模式_如何去除vue项目中的#

在使用vue-cli搭建的环境中,浏览器上URL地址中是存在#的,这是由于vue-router 默认 hash 模式,不难发现#的出现真的很丑陋。官网给出了如何使用history模式mode: history

vue路由传参主要的3种方式

vue中路由传参主要的3种方式:query方式(push时使用path来匹配)、params模式(push时使用name来匹配)、location预声明参数模式(push使用path来匹配,但是它跟params模式不同)

vue动态加载路由_实现vue动态加载路由器设置

我们的通用的后台管理系统中,我们会根据权限的粗细不同,会对每个角色每个权限每个资源进行控制。同样的我们也需要实现一个这样的功能。 这篇文章我将主要讲vue端的实现,关于后台接口我就不会涉及,当我接触的时候我们的后台接口是springcloud实现。

两种前端路由的实现方式

前后端分离开发模式,后端会把路由控制丢在前端,这几天再开发单页面小的项目,手动撸了个路由。前端路由实现有两种方法。HTML5 History API包括2个方法:history.pushState()和history.replaceState(),和1个事件:window.onpopstate。hash + location.onhashchange

vue动态路由_vue-router通过接口请求动态生成路由的实现

在后台管理系统中,一般都会采用权限管理。路由菜单数据都会保存到数据库中,在vue-router 2.2版本新增了一个router.addRoutes(routes)方法,即可用它来实现动态路由了

HTML5 History 模式

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

vue router 路由鉴权(非动态路由)

原本想用动态路由的思路去做,按权限加载对应路由表,但是由于权限可以交叉(比如一个人可以同时是主题管理员和数据服务管理员),导致权限路由表还是得去做判断组合。于是放弃了这个思路,索性就在beforeEach里直接判断了。

vue中路由按需加载的几种方式

使用vue-cli构建项目后,我们会在Router文件夹下面的index.js里面引入相关的路由组件,webpack在打包的时候会把整个路由打包成一个js文件,如果页面一多,会导致这个文件非常大,加载缓慢

vue-router 中参数传递(params,query)

query和params的区别,query相当于get请求,在页面跳转的时候,可以在地址栏看到请求参数,然而params则相当于post请求,参数不会在地址栏中显示。

Node.js的路由

当服务端接收到HTTP请求时,可以通过onRequest() 获取到url, pathname,query,及paramParams参数;为了解析这些数据需要使用url和querystring模块

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!