hash与history原理

hash

首次加载 首次进入页面主动获取地址栏的hash值 用hash值去匹配路由规则 找到要渲染的组件进行渲染
监听hashChange事件 当hash值发生变化获得新的hash值 根据路由规则去渲染组件

export default {
  name: "router-view",
  data() {
    return {
      component: null,
    };
  },
  render(h) {
    return h(this.component); //显示组件
  },

  methods: {
    renderView() {
      // 获得hash值
      let hashValue = "";
      if (location.hash) {
        hashValue = location.hash.replace("#", "");
      } else {
        hashValue = "/";
        location.hash = "#/";
      }
      // 获得处理好的hash值,找到要渲染的组件。
      const routes = this.$router.$options.routes;
      const { component } = routes.find((route) => hashValue === route.path); //Home
      // 设置要渲染的组件给data上的属性,可以重新渲染组件
      this.component = component;
    },
  },

  mounted() {
    // 刚进入项目,手动刷新
    /* window.addEventListener('load', ()=>{
      console.log('load');
    }) */
    // 直接在mounted方法中处理hash值
    this.renderView();

    // 监听地址栏的hash值的变化
    window.addEventListener("hashchange", () => {
      this.renderView();
    });
  },
};

history

首次进入页面获取地址栏的pathName地址 根据地址去匹配路由规则 找到对应的组件进行渲染 当路由发生变化不是直接修改地址 通过pushState事件去修改地址 而不是重新请求服务器 当地址栏发生回退事件 需要监听popstate事件
根据新的地址进行渲染

export default {
  name: "router-view",
  data() {
    return {
      component: null,
    };
  },
  render(h) {
    return h(this.component);
  },
  methods: {
    renderView() {
      // 获得path
      const path = location.pathname;

      // 根据路由规则找到对应路径的组件
      const routes = this.$router.$options.routes;
      const { component } = routes.find((route) => route.path === path);
      this.component = component;
    },
  },
  mounted() {
    // 首次进入,手动刷新
    this.renderView();

    // 监听eventBus中的path-change事件
    this.$eventBus.$on("path-change", () => {
      this.renderView();
    });

    // 监听返回事件
    window.addEventListener('popstate', ()=>{
      this.renderView();
    })
  },
};

以上代码只是简单的实现了路由的跳转 其余的功能并不具备

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值