大前端学习 -- 手写 Vue Router

举报
楚楚冻人玥玥仙女 发表于 2021/11/19 01:17:06 2021/11/19
【摘要】 手写 Vue Router Vue-Router 代码仓库地址: https://gitee.com/jiailing/lagou-fed/tree/master/fed-e-task-...

手写 Vue Router

Vue-Router

代码仓库地址:
https://gitee.com/jiailing/lagou-fed/tree/master/fed-e-task-03-01/code/06-my-vue-router

vue-router核心代码:

App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/ablout">About</router-link>
    </div>
    <router-view/>
  </div>
</template>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

router/index.js

// 注册插件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }
]

const router = new VueRouter({
  routes
})

export default router


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

const vm = new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
console.log(vm)


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

一、动态路由

router/index.js

const routes = [
  {
    path: '/',
    name: 'Index',
    component: Index
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    // 开启props,会把URL中的参数传递给组件
    props: true,
    // 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/Detail.vue')
  }
]


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

view/Detail.vue

<template>
  <div>
    这是Detail页面
    <!-- 方式一:通过当前路由规则,获取数据 -->
    通过当前路由规则获取:{{ $route.params.id }}

    <br>

    <!-- 方式二:路由规则中开启props传参  (推荐)-->
    通过开启props获取: {{ id }}
  </div>
</template>

<script>
export default {
  name: 'Detail',
  // 将路由参数配置到props中
  props: ['id']
}
</script>


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

二、嵌套路由

router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../components/Layout.vue'
import Login from '../views/Login.vue'
import Index from '../views/Index.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  // 嵌套路由
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'index',
        component: Index
      },
      {
        path: 'detail/:id',
        name: 'detail',
        props: true,
        component: () => import('@/views/Detail.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

export default router


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

components/Layout.vue

<template>
  <div>
    <div>
      <img width='80px' src='@/assets/logo.png'>
    </div>
    <div>
      <router-view></router-view>
    </div>
    <div>
      Footer
    </div>
  </div>
</template>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

三、编程式导航

View/Index.vue

<template>
  <div>
    <router-link to="/">首页</router-link>
    <button @click="replace"> replace </button>
    <button @click="goDetail"> Detail </button>
  </div>
</template>

<script>
export default {
  name: 'Index',
  methods: {
    replace () {
      this.$router.replace('/login')
    },
    goDetail () {
      this.$router.push({ name: 'Detail', params: { id: 1 } })
    }
  }
}
</script>


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

View/Detail.vue

<template>
  <div>
    这是Detail页面

    路由参数: {{ id }}

    <button @click="go"> go(-2) </button>
  </div>
</template>

<script>
export default {
  name: 'Detail',
  // 将路由参数配置到props中
  props: ['id'],
  methods: {
    go () {
      this.$router.go(-2)
    }
  }
}
</script>


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

四、Hash模式和History模式

1. 表现形式的区别

  • Hash模式:http://localhost/#/detail?id=1234
  • History模式:http://localhost/detail/1234

2. 原理的区别

  • Hash模式是基于锚点,以及onHashChange事件。
  • History模式是基于HTML5中的History API
    • History.pushState() IE10以后才支持
    • History.replaceState()

3. History模式的使用

  • History需要服务器的支持

  • 单页应用中,服务端不存在http://www.test.com/login这样的地址会返回找不到该页面

  • 在服务端应该除了静态资源外都返回单页应用的index.html

  • Node.js服务器配置

    const path = require('path')
    // 导入处理 history 模式的模块
    const history = require('connect-history-api-fallback')
    // 导入 express
    const express = require('express')
    
    const app = express()
    // 关键:注册处理 history 模式的中间件
    app.use(history())
    // 处理静态资源的中间件,网站根目录 ../web
    app.use(express.static(path.join(__dirname, '../web')))
    
    // 开启服务器,端口是 3000
    app.listen(3000, () => {
      console.log('服务器开启,端口:3000')
    })
    
        
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • Nginx服务器配置

    # 启动
    start nginx
    # 重启
    nginx -s reload
    # 停止
    nginx -s stop
    
        
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

nginx.conf

http: {
	server: {
		location / {
			root html;
			index index.html index.htm;
			# 尝试查找,找不到就回到首页
			try_files $uri $uri/ /index.html;
		}
	}
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4. Hash模式

  • URL中#后面的内容作为路径地址
  • 监听hashchange事件
  • 根据当前路由地址找到对应组件重新渲染

5. History模式

  • 通过History.pushState()方法改变地址栏(不会向服务器发送请求,但会将这次URL记录到历史中)
  • 监听popstate事件
  • 根据当前路由地址找到对应组件重新渲染

五、实现自己的vue-router

Vue的构建版本

  • 运行时版:不支持template模板,需要打包的时候提前编译

    • 使用render函数

      Vue.component('router-link', {
            props: {
              to: String
            },
            render (h) {
              return h('a', {
                attrs: {
                  href: this.to
                },
                
              }, [this.$slots.default])
            },
            // template: '<a href="to"><slot></slot></a>'
          })
      
            
           
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
  • 完整版:包含运行时和编译器,体积比运行时版本大10k左右,程序运行的时候把模板转换成render函数

    • 在项目根目录下增加一个文件:vue.config.js

      module.exports = {
        // 完成版本的Vue(带编译器版)
        runtimeCompiler: true
      }
      
            
           
      • 1
      • 2
      • 3
      • 4

最终代码:

Vuerouter/index.js

let _Vue = null

export default class VueRouter {
  static install (Vue) {
    // 1. 判断当前插件是否已经被安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 2. 把Vue构造函数记录到全局变量
    _Vue = Vue
    // 3. 把创建Vue实例时候传入的router对象注入到Vue实例上
    // 混入
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  constructor (options) {
    this.options = options
    this.routeMap = {}
    // _Vue.observable创建响应式对象
    this.data = _Vue.observable({
      current: '/'
    })
  }

  init () {
    this.createRoutMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  createRoutMap () {
    // 遍历所有的路由规则,把路由规则解析成键值对的形式,存储到routeMap中
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          // 事件
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          history.pushState({}, '', this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
      // template: '<a href="to"><slot></slot></a>'
    })
    const self = this
    Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }

  initEvent () {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })
  }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84

Router/index.js

// ....

import VueRouter from '../vuerouter'

// ....

  
 
  • 1
  • 2
  • 3
  • 4
  • 5

文章来源: blog.csdn.net,作者:爱玲姐姐,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jal517486222/article/details/107444444

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200