其实这算是一个取巧的办法,如果使用在vue中使用 addEventListener('storage') 的话,需要符合指定的条件,用起来还是有一些麻烦的,所以如果大家在项目中有需要监听本地存储的变化可以参考一下下面的做法。
<template>
<div>
<button @click="curBtn">存储</button>
</div>
</template>
<script>
export default {
data() {
return {
Num:0
}
},
watch: {
watSessName: {
handler(newValue, oldValue) {
console.log(newValue, '新值====');
console.log(oldValue, '旧值====');
}
}
},
component: {
watSessName() {
return this.Num + '-' +sessionStorage.getItem('keyName')
}
},
methods: {
curBtn() {
sessionStorage.setItem('keyName', Math.random() * 1000);
this.Num++;
}
},
}
</script>
根据大家在项目中的场景进行使用!