[TOC]

前端路由 router 原理

两种方式:hash,history

hash介绍

  • url有个#符号,但是#只是客户端得状态,实不会传来服务器
  • hash得更改,不会导致页面更新
  • hash得更改,会在浏览器的访问历史中添加一条记录,所以我们可以通过浏览器得返回前端按钮控之hash得切换
  • hash得更改,会触发 haschange 事件,实例:

    location.hash = '#aaa';
    location.hash = '#bbb';
    window.addEventListenter('hashchange', () => {});
    
  • html标签得方式

    <a href="#user">点击跳转</a> 
    等同于
    location.hash = '#user';
    

hash路由原理代码

<div class="box">
    <a href='#red'>红色</a>
    <a href='#orange'>橙色</a>
    <a href='#yellow'>黄色</a>
    <a href='#green'>绿色</a>
</div>
<script>
    class Router {
        constructor() {
            this.routes = {}; // 初始化路由对象
            window.addEventListener('hashchange', () => {
                this.refresh();
            })
        }

        route(path, callback) {
            this.routes[path] = callback || function () {} // key => 路由  value => 路由对应的事件
        }

        refresh() {
            const hashUrl = `/${location.hash.slice(1)}`; // #red =>  /red
            this.routes[hashUrl]();
        }
    }

 const router = new Router();
 router.route('/red', function() {
     document.querySelector('body').style.background = 'red';
 })
 router.route('/orange', function() {
     document.querySelector('body').style.background = 'orange';
 })
 router.route('/yellow', function() {
     document.querySelector('body').style.background = 'yellow';
 })
 router.route('/green', function() {
     document.querySelector('body').style.background = 'green';
 })
</script>

history

  • html history用法

    window.history.back(); // 后退
    window.history.forward(); // 前进
    window.history.go(-1); // 接收number,后退1页
    window.history.pushState();
    window.history.replaceState();
    
  • pushState和replaceState的参数

    • state:是一个对象,是一个与指定网址相关的对象,当popstate事件触发的时候,该对象会传入回调函数
    • title:新页面的标题,浏览器支持不一,null
    • url:页面的新地址
  • history特点

    • 没有#
    • pushState/replaceState 并不会触发 popstate 事件,这是我们需要手动触发页面的重新渲染
    • 可以用popstate来监听url的变化
    • popstate到底什么才能触发
      • 点击浏览器前进/后退按钮
      • 调用back/forward/go方法
    • 面试题:vue-router怎么记住前一个页面的滚动条的位置image.png

      • 手动点击浏览器的返回或前进,基于history的go,back,forward,back
      • router-link是不能记住的

        history路由原理代码

        ```html

        返回

        ```

        手写表单组件

      • 表单组件里面用到校验部分:JSON schema,配置一组数据判断你的东西是否满足这个条件image.png

      • 简单分析一波,就是一个表单组件,但是不是一个组件是由form, form-item, input组成的,先看看页面使用的代码

        <j-form ref="form" :model="formModel" :rules="formRules">
        <j-form-item label="名称" prop="name">
            <j-input v-model="formModel.name"></j-input>
        </j-form-item>
        <j-form-item label="邮箱" prop="email">
            <j-input v-model="formModel.email"></j-input>
        </j-form-item>
        </j-form>
        
        • 这里传入几个值
          • ref,待会用来调用表单的校验方法的
          • model,传进去整个表单的值对象
          • formRules,这里校验表单的对象
        • 还有个很重要的方法,这个

          export default {
          methods: {
            /**
             * @Description 向上一直查找直到找到有这个函数名的函数,调用父级的方法emit
             **/
            dispatch(componentName, eventName, params) {
                let parent = this.$parent || this.$root; // 拿到当前的父级
                let name = parent.$options.name; // 拿到父级的name
                const args= [eventName].concat(params); // 数组参数, 【方法名,其他参数】
                while (parent && (!name || name !== componentName)) { // 判断月
                    parent = parent.$parent;
                    if (parent) name = parent.$options.name;
                }
                if (parent) parent.$emit.apply(parent, args);
               // 例如,如果是找form组件里面的add方法,就等价于在form组件里面 this.$emit('add', 'agr1', 'arg2')
              // 感觉可以不用emit,直接调用这个方法 parent[eventName].call(parent, ...arg) 这样会更方便一点
            }
          }
          }
          
        • 下面看看每个组件的主要代码

          <script>
          export default {
            name: "JForm",
            data() {
                return {
                    fields: [ ]
                }
            },
            // model:就是里表单保存的数据 rules:表单的规则
            props: ['model', 'rules'],
            // 这里把表单的this提供出去,为了给下面的form-item,和input使用到父组件的东西
            provide() {
                return {
                    form: this
                }
            },
            methods: {
                /**
                 * @Description 是否通过校验
                 **/
                validate() {
                    return new Promise(resolve => {
                        this.fields.forEach(field => { // 调用每个子组件的的validate的来校验
                                field.validate('', error => {
                                    console.log(error )
                                })
                        });
                        resolve();
                    })
                }
            },
            created() {
                /**
                 * @Description 这里监听form-add事件,把里面的传来的子组件push进变量field,push进来的是整个子组件,就是子组件的this
                 **/
                this.$on('form-add', field => {
                    if (field) this.fields.push(field)
                })
            }
          }
          </script>
          

          ```html

      ```html
      <!-- 这个就不注释了,常规操作了 -->
      <template>
          <input ref="input"
                 :value="currentValue"
                 @input="handelInput"
                 @blur="handelBlur"
                 :type="type">
      </template>
      
      <script>
          import EventEmitter from '../../formUtil';
          export default {
              name: "JInput",
              mixins: [EventEmitter],
              props: ['type', 'value'],
              data() {
                  return {
                      currentValue: this.value,
                      id: this.label
                  }
              },
              methods: {
                  handelInput(e) {
                      const value = e.target.value;
                      this.currentValue = value;
                      this.$emit('input', value);
                      this.dispatch('JFromItem', 'form-change', value)
                  },
                  handelBlur() {
                      this.dispatch('JFromItem', 'form-blur', this.currentValue)
                  }
              },
              mounted() {
                  if (this.$parent.labelFor) {
                      this.$refs.input.id = this.$parent.labelFor;
                  }
              },
              watch: {
                  value(value) {
                      this.currentValue = value;
                  }
              }
          }
      </script>
      

      vue核心源码解析

      • 劫持数据
      • getter触发收集依赖、setter触发更新
      • dom结构转换为vnode
      • vnode的diff算法,决定哪个平台的最终渲染

      认识flow:静态检测工具

      • 类型推断: 上下文推断
      • 类型注释: 通过我们期待好的类型的注释来判断