在web端,每次切换tab或不同状态后,刷新页面,希望上次切换的状态能够还原;

  1. 方案一,通过uni.setStorageSync储存本地,刷新后读取;
  2. 方案二,通过改变url,被动刷新后,再从onLoad中读取转态,主要讲此方案,需要用到window.history中replaceState方法;
window.history       // 属性指向 History 对象,它表示当前窗口的浏览历史。

/**
 * 将当前的历史记录给替换掉,不会刷新页面,不会在history中留下记录
 * @param  {Obj} stateObj  态对象是一个JavaScript对象,它与传递给 replaceState 方法的历史记录实体相关联.一般为空;
 * @param  {string} title  标题,大部分浏览器忽略这个参数,一般空串;
 * @param  {string} url  新的URL跟当前的URL必须是同源;
 */
window.history.replaceState(stateObj, title, url);
  • 示例代码
<template>
    <view class="content">
        <image class="logo" src="/static/logo.png"  @tap="onClick"></image>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                oldhash: ''
            }
        },
        onLoad(options) {
            console.log(window.location);
            this.oldhash = window.location.hash;
        },
        methods: {
            onClick(){
                var url = this.oldhash + '?id=1';
                window.history.replaceState(null, '',url);
            }
        }
    }
</script>

<style>
    .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .logo {
        height: 200rpx;
        width: 200rpx;
        margin-top: 200rpx;
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 50rpx;
    }
</style>
  • 变化
// 改变前
http://localhost:8080/#/pages/index/index
// 改变后
http://localhost:8080/#/pages/index/index?id=1

点赞(0)

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

返回
顶部