<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 修改成你要監聽的值即可