<template><div class="specific-storage-watcher"><h3>仅监听 userId 变化</h3><p>当前 userId: {{ currentUserId }}</p><p v-if="changeRecord">最近变化: {{ changeRecord }}</p><button @click="updateUserId">修改 userId(测试)</button></div>
</template><script>
export default {data() {return {currentUserId: sessionStorage.getItem('userId') || '未设置',changeRecord: '',originalSetItem: null,// 添加标识,防止重复重写isOverridden: false}},mounted() {// 安全校验:确保原生方法存在且未被当前组件重写过if (sessionStorage.setItem && !this.isOverridden) {this.originalSetItem = sessionStorage.setItemconst _this = thissessionStorage.setItem = function(key, newValue) {// 再次校验原生方法是否存在if (!_this.originalSetItem) returnif (key === 'userId') {const oldValue = sessionStorage.getItem('userId')_this.originalSetItem.call(sessionStorage, key, newValue)_this.handleUserIdChange(oldValue, newValue)} else {_this.originalSetItem.call(sessionStorage, key, newValue)}}this.isOverridden = true}// 为 storage 事件绑定具名函数(方便移除)this.handleStorageEvent = (e) => {if (e.key === 'userId') {this.handleUserIdChange(e.oldValue, e.newValue)}}window.addEventListener('storage', this.handleStorageEvent)},beforeDestroy() {// 安全恢复原生方法if (this.originalSetItem && this.isOverridden) {sessionStorage.setItem = this.originalSetItemthis.isOverridden = false}// 移除具名事件监听(避免内存泄漏)window.removeEventListener('storage', this.handleStorageEvent)},methods: {handleUserIdChange(oldValue, newValue) {this.currentUserId = newValue || '已删除'this.changeRecord = `从 "${oldValue || '无'}" 变为 "${newValue || '无'}"`console.log('userId 发生变化:', this.changeRecord)},updateUserId() {const newId = 'user_' + Math.floor(Math.random() * 1000)sessionStorage.setItem('userId', newId)}}
}
</script><style scoped>
/* 样式保持不变 */
.specific-storage-watcher {padding: 20px;font-family: Arial, sans-serif;
}button {margin-top: 10px;padding: 6px 12px;cursor: pointer;
}p {margin: 8px 0;
}
</style>
代码里面userId 修改成你要监听的值即可