前端路由模拟(hash值、history、Vue)

13 篇文章 0 订阅

前端路由模拟(hash值、Vue)

  • 创建三个简易的子组件
  <script type="text/x-template" id="home">
    <div>
      <h1>home</h1>
    </div>
  </script>
  <script type="text/x-template" id="profile">
    <div>
      <h1>profile</h1>
    </div>
  </script>
  <script type="text/x-template" id="cart">
    <div>
      <h1>cart</h1>
    </div>
  </script>
const home = {
      template: '#home'
    }
    const profile = {
      template: '#profile'
    }
    const cart = {
      template: '#cart'
    }
  • 父组件
  <div id="app">
    <a href="#/home">Home</a>
    <a href="#/profile">profile</a>
    <a href="#/cart">cart</a>
    <component :is="comName"></component>
  </div>
    const vue = new Vue({
      el: '#app',
      data: {
        comName: 'home'
      },
      components: {
        home,
        profile,
        cart
      },
      methods: {
        hChange() {
          window.onhashchange =  () => {
            this.comName = location.hash.slice(2);
            return;
          }
        }
      }
    })

在这里插入图片描述

  • 点击a标签会将url上添加/#/对应组件名的锚点,我们可以通过window.onhashChange事件方法来监听loacation.hash的变化,变化就会触发。
    在这里插入图片描述
  • 我们只用将<compontent>标签上的is属性修改为对应的组件名就可以了(一定要是字符串类型的组件名)
  • window.onhashChange事件方法最后接箭头函数,因为this的指向问题。

前端路由模拟(history、Vue)

  • 跟在Vue用mode:history一样的情况跳转路由之后不可以刷新,不然他就会请求原本路径+‘/xx’的文件了。
  • 子组件
  <script type="text/x-template" id="home">
    <div>
      <h1>home</h1>
    </div>
  </script>
  <script type="text/x-template" id="profile">
    <div>
      <h1>profile</h1>
    </div>
  </script>
const home = {
      template: '#home'
    }
    const profile = {
      template: '#profile'
    }
    const cart = {
      template: '#cart'
    }
  • 父组件
  <div id="app">
    <a href="javascript:void(0)" @click="changeUrl('home')">Home</a>
    <a href="javascript:void(0)" @click="changeUrl('profile')">profile</a>
    <component :is="comName"></component>
  </div>
const vue = new Vue({
      el: '#app',
      data: {
        comName: 'home'
      },
      components: { // 组件不用说
        home,
        profile
      },
      methods: {
        changeUrl(com) {
        // url路径修改但是不会请求资源和刷新
          history.pushState(null, null, this.LocationHref + com); 
          this.comName = com; // 修改component标签中的is属性达到子组件的替换
        }
      },
      mounted() {
        this.LocationHref = location.href + '/'; // 拿到当前页面的href
      }
    })
  • mode: history刷新时之所以会出现访问不到页面的原因就是history.pushState()导致url改变之后,刷新会请求当前路径下的资源,而我们当前路径根本没有对应资源,只是我们写的路由而已,所以刷新之后请求不到对应的页面。
  • hash可以刷新的原因是不会请求/#/xx这样的锚点当做资源。
  • history模式下只能在服务器路径下即http://127.0.0.1/xxx这种情况下,而无法在电脑目录上运行file:///E:/xxx.html在这种目录下,history模式url改变会请求对应目录下的资源。

每天一个脱发小技巧 —— 菜鸡

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值