首页 前端知识 vue如何监听sessionStorage的某个值是否发生变化

vue如何监听sessionStorage的某个值是否发生变化

2024-08-21 22:08:23 前端知识 前端哥 517 708 我要收藏

在Vue中,sessionStorage的更改并不会自动触发Vue的响应式系统,因为sessionStorage不是Vue的响应式数据源。要监听sessionStorage中某个值的变化,需要手动设置一个监听器。
以下是一个在Vue组件中监听sessionStorage某个值变化的示例:

<template>
<div>
<!-- 其他组件代码 -->
</div>
</template>
<script>
export default {
data() {
return {
watchedKey: 'myKey', // 要监听的sessionStorage的键
watchedValue: null, // 初始化时从sessionStorage获取的值
};
},
created() {
// 在组件创建时设置对sessionStorage的监听
this.updateWatchedValue();
window.addEventListener('storage', this.handleStorageEvent);
},
beforeDestroy() {
// 在组件销毁前移除监听器
window.removeEventListener('storage', this.handleStorageEvent);
},
methods: {
updateWatchedValue() {
this.watchedValue = sessionStorage.getItem(this.watchedKey);
},
handleStorageEvent(event) {
// 检查是否是监听的键发生了变化
if (event.key === this.watchedKey) {
// 更新数据
this.updateWatchedValue();
// 触发Vue的响应式更新
this.$forceUpdate();
}
},
},
watch: {
watchedValue(newValue, oldValue) {
// 当监听的sessionStorage值变化时,这里的逻辑会执行
console.log(`The value of '${this.watchedKey}' in sessionStorage changed from '${oldValue}' to '${newValue}'`);
},
},
};
</script>
复制

在这个例子中,watchedKey是你要监听的sessionStorage的键。在created钩子中,我们设置了一个监听器handleStorageEvent来监听storage事件,这个事件会在sessionStorage发生变化时触发。

当sessionStorage中的值发生变化时,handleStorageEvent方法会被调用,并且我们可以检查event.key来确定是不是我们关心的键。如果是,我们就更新watchedValue的值,并调用this.$forceUpdate()来强制Vue重新渲染组件,因为watchedValue是一个响应式数据。

同时,我们在beforeDestroy钩子中移除了storage事件的监听器,以避免潜在的内存泄漏。

注意,storage事件不仅仅会在当前窗口触发,也会在同一个浏览器标签页中的其他窗口或标签页中触发,因为它们共享同一个sessionStorage。因此,这个监听器会在整个浏览器标签页范围内对sessionStorage的变化做出响应。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/16482.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

安装Nodejs后,npm无法使用

2024-11-30 11:11:38

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!