window.location.hash的小妙用

本文介绍如何利用JavaScript中的location.hash属性实现网页内的Tab切换功能,包括如何在Vue.js项目中进行具体操作,并确保浏览器历史记录正确更新。

location是javascript里边管理地址栏的内置对象,比如location.href就管理页面的url,用location.href=url就可以直接将页面重定向url。而location.hash则可以用来获取或设置页面的标签值。比如http://domain/#admin的location.hash="#admin"。

通过window.location.hash=hash这个语句来调整地址栏的地址,使得浏览器里边的“前进”、“后退”按钮能正常使用(实质上欺骗了浏览器)。然后再根据hash值的不同来显示不同的面板(用户可以收藏对应的面板了)

比如常见的就是点击切换tab,显示不同tab对应的内容,页面刷新再次进来自动定位到上次停留的tab对应的内容。

举个最近小活动中的例子:

vue中template中:
<ul :class="['bar-box',tableBg]"  >
      <li @click="changeBG('1')"></li>
      <li @click="changeBG('2')"></li>
      <li @click="changeBG('3')"></li>
</ul>
对应的tab下面的内容:
<div class="tab1-box"  v-if="current===1"></div>
<div class="tab1-box"  v-if="current===2"></div>
<div class="tab1-box"  v-if="current===3"></div>


mounted的时候判断一下上次浏览的tab内容并显示:
    
     if(window.location.href.indexOf("#tab") > -1 ){
      this.current = Number(window.location.href.split("#tab")[1]);
      window.location.hash = "tab" + this.current
    }else{
      this.current =1;
      window.location.hash = "tab" + this.current;
    }


methods对应的btn点击事件:
//tab切换
changeBG(x) {

    this.current = Number(x);

    window.location.hash = "tab" + this.current;

    this.tableBg ="bar-box" + this.current;

},

这样就很容易啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值