LocalStorage本地存储记录历史记录,歌曲播放时间,进度条

本文介绍了如何利用localStorage和sessionStorage存储字符串对象,详细讲解了如何记录搜索历史和歌曲播放进度,以及如何通过parse和stringify操作JSON数据。还探讨了它们的生命周期和浏览器共享特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

localStorage和sessionStorage

前者生命周期是永远,sessionStorage的生命周期是当前窗口或当前标签页,
两者都能够存储字符串类型的对象,不同浏览器不能共享localStorage中的信息

parse

JSON字符串转为对象

stringify

对象转JSON字符串转

记录搜索历史记录

async beforeMount() {
    if (localStorage.historyList != undefined && localStorage.historyList != "") {  // parse方法,将JSON字符串转为数组对象
        this.historyList = JSON.parse(localStorage.historyList)
        this.isShow = true
    } else {
        this.isShow = false
    }
    this.defaulttSearchKey = this.$route.query.defaulttSearchKey;
}
eventFn() { //回车事件
	this.historyList = this.historyList.reverse(); //数组反转
	this.historyList.push(this.keyword); //将新输入的关键词push到数组
	this.historyList = this.historyList.reverse(); //再次将数组反转
	this.historyList = Array.from(new Set(this.historyList)); //去除重复值
	localStorage.historyList = JSON.stringify(this.historyList);//数组转为字符
}

记录歌曲播放时间,进度条

// 进度条
let progress = this.$refs.audio.currentTime / localStorage.duration;
this.$store.commit("setProgress", progress);
progress = parseInt(progress * 100)
this.tempRate = progress;
this.rate = this.tempRate;
// 播放时间
if (this.paused) {
    return;
}
if (localStorage.duration != "NAN" && localStorage.duration && !this.duration) {
    this.duration = localStorage.duration;
}
// 设置当前播放时间
this.$store.commit('setCurrentTime', this.$refs.audio.currentTime);
let progress = this.currentTime / this.duration;
// 设置进度条
this.$store.commit("setProgress", progress);

无论是历史记录、进度条还是播放时间这里都保存在了store里,可在全局进行存取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值