vue2 watch监听sessionstorage 监听不到
时间: 2023-11-19 13:55:24 浏览: 74
根据提供的代码,可能是因为watch监听的是sessionStorage对象本身,而不是sessionStorage中某个具体的key值。因此,当sessionStorage中的某个key值发生变化时,watch监听不到。解决方法是在sessionStorage中的某个key值发生变化时,手动触发一个事件,让watch监听到这个事件,从而实现监听sessionStorage中某个key值的变化。
代码实现如下:
```
// 监听sessionStorage中某个key值的变化
watch: {
'$store.state.sessionStorageKey': function (newVal, oldVal) {
console.log('sessionStorageKey changed:', newVal, oldVal)
}
},
// 手动触发事件
methods: {
setSessionStorage: function (key, val) {
sessionStorage.setItem(key, val)
this.$store.state.sessionStorageKey = key + Math.random()
}
}
```
相关问题
vue2 watch监听sessionstorage 监听不到变化啊
可以尝试使用第三方库vue-ls来监听sessionStorage的变化。首先需要安装vue-ls,然后在main.js中引入并配置。接着在需要监听的组件中使用watch监听sessionStorage的变化即可。
代码示例:
```javascript
// 安装vue-ls
npm install vue-ls --save
// main.js中引入并配置
import Vue from 'vue'
import VueStorage from 'vue-ls'
Vue.use(VueStorage, {
namespace: 'vuejs__', // key prefix
name: 'ls', // name variable Vue.[ls] or this.[$ls],
storage: 'session' // storage name session, local, memory
})
// 组件中使用watch监听sessionStorage的变化
export default {
data() {
return {
role: this.$ls.get('role') // 初始化时获取sessionStorage中的值
}
},
mounted() {
// 监听sessionStorage的变化
this.$watch('$ls.role', (val) => {
this.role = val
})
}
}
```
vue2 watch 监听sessionstorage
Vue2中的watch属性可以监听数据的变化并做出相应的响应。如果你想要监听sessionStorage中的数据变化,可以使用Vue的watch属性和sessionStorage的API来实现。具体步骤如下:
1. 定义一个Vue实例
```
var vm = new Vue({
// ...
})
```
2. 使用Vue的watch属性监听sessionStorage中的数据变化
```
vm.$watch(function() {
return sessionStorage.getItem('key')
}, function(newValue, oldValue) {
// 在这里可以做出响应
})
```
其中,第一个参数是一个函数,用来获取sessionStorage中的数据;第二个参数是一个回调函数,在sessionStorage中的数据变化时触发。在回调函数中,你可以根据新旧值来执行一些逻辑。
注意:如果要监听sessionStorage中多个键值对的变化,需要分别为它们添加watcher。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)