vue watch 监听 window.sessionStorage
时间: 2024-05-24 17:08:19 浏览: 309
Vue中的watch选项可以用来监听一个Vue实例中的数据变化,当数据发生变化时,watch函数会自动执行。而window.sessionStorage是一种浏览器存储机制,可以用来在同一浏览器的不同页面之间共享数据。要在Vue中监听window.sessionStorage的变化,可以通过以下方式进行:
```javascript
watch: {
'$sessionStorage.yourData': function (newValue, oldValue) {
// 监听 window.sessionStorage 中 yourData 的变化
// newValue 为变化后的值,oldValue 为变化前的值
// 这里可以进行相应的操作
}
}
```
在上述代码中,`$sessionStorage` 是 Vue 的插件 `vue-session` 提供的全局属性,可以直接访问 `window.sessionStorage` 中的数据。当 `yourData` 数据发生变化时,`watch` 中定义的函数会自动执行。
相关问题
vue3 监听sessionStorage变化
在Vue3中监听`sessionStorage`的变化,可以借助`watch`或者`MutationObserver` API。以下是两种方法的示例:
**使用 watch 方法:**
```javascript
import { watch } from 'vue';
export default {
setup() {
const handleSessionStorageChange = () => {
// 检查 sessionStorage 是否有更新
if (sessionStorage.getItem('yourKey')) {
console.log('sessionStorage changed');
// 在这里处理更新后的值
}
};
watch(() => sessionStorage, handleSessionStorageChange); // 监听整个 sessionStorage
return { handleSessionStorageChange };
},
}
```
在这个例子中,当`sessionStorage`中的内容改变时,`handleSessionStorageChange`函数会被触发。
**使用 MutationObserver:**
```javascript
import { onMounted } from 'vue';
import { observe } from 'immer'; // 如果你的项目用了 Immer,需要引入这个库
onMounted(() => {
const observer = new MutationObserver(mutationsList => {
mutationsList.forEach(mutation => {
if (mutation.type === 'childList') { // 只关注添加、删除节点的情况
const key = mutation.addedNodes.textContent || mutation.removedNodes.textContent;
console.log(`sessionStorage changed: ${key}`);
// 处理变化
}
});
});
observer.observe(window.sessionStorage, { attributes: false, childList: true, subtree: true }); // 监听指定的对象
});
```
记得在不再需要监控时调用`observer.disconnect()`关闭观察。
vue2监听sessionstorage变化
### Vue2 中监听 `sessionStorage` 变化的实现
在 Vue2 项目中,可以通过监听存储事件来监控 `sessionStorage` 的变化。当其他标签页或窗口中的 `sessionStorage` 发生更改时,当前页面能够接收到通知并作出相应反应。
#### 使用 StorageEvent 实现跨窗口监听
由于浏览器的安全机制,在同一个域下的不同窗口之间共享相同的 `sessionStorage` 数据源。每当调用 `setItem()` 或者 `removeItem()` 方法修改 `sessionStorage` 时,会触发一个名为 `"storage"` 的全局事件[^1]。
```javascript
// main.js or any global setup file in your project
window.addEventListener('storage', function(event) {
if (event.key === 'watchStorage') { // Specify the key you want to watch
console.log(`The value of ${event.key} has changed from ${event.oldValue} to ${event.newValue}`);
// Perform actions based on storage change, such as fetching new data.
fetchDataBasedOnNewSessionData();
}
});
```
对于特定组件内的局部监听,则可以在生命周期钩子内添加自定义逻辑:
```javascript
export default {
created() {
window.addEventListener('storage', this.handleStorageChange);
},
beforeDestroy() {
window.removeEventListener('storage', this.handleStorageChange);
},
methods: {
handleStorageChange(event) {
if (event.key !== null && event.storageArea === sessionStorage && event.key === 'watchStorage') {
const newVal = sessionStorage.getItem('watchStorage');
// Update component state with newValue and perform necessary operations like API calls.
this.updateComponentState(newVal);
}
}
updateComponentState(newValue){
// Your implementation here...
}
fetchDataBasedOnNewSessionData(){
// Fetch updated data using axios etc., according to business requirements.
}
}
}
```
需要注意的是,上述方式仅适用于检测来自外部(即同一域名下其它浏览上下文)发起的变更操作。如果是在同一页内部通过 JavaScript 修改 `sessionStorage` ,则不会触发此事件。因此,针对这种情况,建议采用额外的状态管理策略或者直接观察属性变动[^4]。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)