Vue 如何监听 localstorage的变化
需求
分析
1. 初始想法
computed: {lonlat(){console.log(localStorage.getItem('lonlat'))return localStorage.getItem('lonlat')}},watch: {lonlat(newVal,oldVal){console.log(1002,newVal,oldVal)}},
我们想着用 计算属性 computed 和 watch 监听实现,但根本没有监听到
2. 解决方案
第一种方法:
重写setItem事件,当使用setItem的时候,触发window.dispatchEvent派发事件
具体步骤:
- 我们写一个dispatchEvent派发事件的js文件,放在一个文件夹里面,比如:utils/tool.js代码如下
function dispatchEventStroage () {const signSetItem = localStorage.setItemlocalStorage.setItem = function (key, val) {let setEvent = new Event('setItemEvent')setEvent.key = keysetEvent.newValue = valwindow.dispatchEvent(setEvent)signSetItem.apply(this, arguments)}
}export default dispatchEventStroage
- 在主文件main.js文件中加入一下代码,以便二个vue组件能够触发派发事假
import tool from './utils/tool.js'
Vue.use(tool)
- 在一个vue组件当中向localStorage存储数据,代码如下:
// gsStorename是key名称(存储名称),gsStroe是值,我这里是一个对象,换成json字符串
window.localStorage.setItem('gsStorename', JSON.stringify(gsStore))
- 在另一个vue组件当中监听localStorage数据变化,来赋值,监听要写在mounted ()中,代码如下:
解释:通过addEventListener监听setItemEvent事件来获取新变化的值,e.newValue就是我们的新值,然后用这个值操作其他
mounted () {// 监听localhostStorage的数据变化,结合utils/tool.js配合使用const that = thiswindow.addEventListener('setItemEvent', function (e) {let newdata = JSON.parse(e.newValue)that.order = newdata.orderthat.cart = newdata.cart})},
特别注意:
我刚开始做的时候,考虑不周,没有写const that=this 这一句,我用的如下代码,一直报错,赋值不了,如下代码是错误的,
为什么要用const that=this这一个呢?
那是因为在JavaScript中,this代表的是当前对象,他是会随程序运行不停改变的,
如果用this的话,this是addEventListener监听中当前的对象,所以赋值的时候不能赋值到外面去。
const that = this 其实就是在this改变之前先复制一份给that,那么在程序后面的运行中就可以用that来赋值该函数以外的对象了,比如that.order
第二种方法:用 vuex
利用 const that=this,可以将值存进store中,
this.od2Visible = true;this.title = '舰船航线规划';this.$store.commit("tools/setzhk", 'od5');var tempList = [];const that = this;var handler = new Cesium.ScreenSpaceEventHandler(window.viewer.scene.canvas); // 创建鼠标事件handlerhandler.setInputAction(function(click) { // 监听鼠标左键点击事件// 获取点击位置的地球坐标var cartesian = window.viewer.camera.pickEllipsoid(click.position, window.viewer.scene.globe.ellipsoid);// 转换为笛卡尔坐标系 let cartographic1 = Cesium.Cartographic.fromCartesian(cartesian);// 转换为经纬度var latitude = Cesium.Math.toDegrees(cartographic1.latitude);var longitude = Cesium.Math.toDegrees(cartographic1.longitude);tempList.push(longitude,latitude)if (cartesian) {var entity = window.viewer.entities.add({ // 在该位置添加点position: cartesian,point: {pixelSize: 10,color: Cesium.Color.YELLOW}});}localStorage.setItem('lonlan',tempList)that.$store.commit("tools/setlonlat", tempList);console.log(1001,that)}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
然后再使用 用 计算属性 computed 和 watch 监听实现
computed: {lonlat(){return this.$store.state.tools.lonlat}},watch: {lonlat(newVal,oldVal){console.log(1002,newVal,oldVal)}},