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;
},
这样就很容易啦
本文介绍如何利用JavaScript中的location.hash属性实现网页内的Tab切换功能,包括如何在Vue.js项目中进行具体操作,并确保浏览器历史记录正确更新。
395

被折叠的 条评论
为什么被折叠?



