在日常开发中,我们经常使用localStorage来存储一些变量。这些变量会存储在浏览中。对于localStorage来说,即使关闭浏览器,这些变量依然存储着,方便我们开发的时候在别的地方使用。
存储值:window.localStorage.setItem(‘键名’, 值)
读取值:window.localStorage.getItem('‘键名’)
- export default function dispatchEventStroage() {
- const signSetItem = localStorage.setItem
- localStorage.setItem = function (key, val) {
- let setEvent = new Event('setItemEvent')
- setEvent.key = key
- setEvent.newValue = val
- window.dispatchEvent(setEvent)
- // eslint-disable-next-line prefer-rest-params
- signSetItem.apply(this, arguments)
- }
- }
2. 在main.js中引入并挂载
- import dispatchEventStroage from './utils/watchLocalStorage'
- Vue.use(dispatchEventStroage);
3.在需要监听的地方使用如下代码
- mounted () {
- // 监听localhostStorage的数据变化,结合utils/tool.js配合使用
- const that=this
- window.addEventListener('setItemEvent', function (e) {
- if (e.key === 'myKey') { // myKey是需要监听的键名
- that.mykey = e.newValue;
- console.log(JSON.parse(e.newValue)) // 这里的newValue就是localStorage中,键名为myKey对应的变化后的值。
- console.log('本地存储值发生变化:', e.newValue)
- }
- })
- },
特别注意:
我刚开始做的时候,考虑不周,没有写const that=this 这一句,我用的如下代码,一直报错,赋值不了,如下代码是错误的,
为什么要用const that=this这一个呢?
那是因为在JavaScript中,this代表的是当前对象,他是会随程序运行不停改变的,
如果用this的话,this是addEventListener监听中当前的对象,所以赋值的时候不能赋值到外面去。
const that = this 其实就是在this改变之前先复制一份给that,那么在程序后面的运行中就可以用that来赋值该函数以外的对象了,比如that.order
利用 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); // 创建鼠标事件handler
- handler.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)
- }
- },