zoukankan      html  css  js  c++  java
  • vue中本地储存也可以实时监听

    网上看到的这个方法 在项目里使用了 贼爽啊,分享下

    比如 在同一个页面里边 不同位置  两个变量的呈现都是使用的本地储存且一个变量修改,第二个变量也要实时变化 在正常情况下 修改一个的值后储存起来 在不刷新页面的情况下 另一个是不会变化的,所以就要用到本地储存的实时刷新

    1. 现在main.js中注册全局方法,比如要监听的本地储存key值为‘changeData’

    Vue.prototype.resetSetItem = function (key, newVal) {
       if (key === 'changData') {
    
           // 创建一个StorageEvent事件
           var newStorageEvent = document.createEvent('StorageEvent');
           const storage = {
               setItem: function (k, val) {
                   sessionStorage.setItem(k, val);
    
                   // 初始化创建的事件
                   newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
    
                   // 派发对象
                   window.dispatchEvent(newStorageEvent)
               }
           }
           return storage.setItem(key, newVal);
       }
    }

    2 如何触发
    在一个路由(比如路由A)存储值得时候,使用下面的方法:

    this.resetSetItem('changeData', this.value);

    3、如何监听
    如果在另外一个路由(比如路由B)中,我们想根据changeData的变化来请求接口刷新页面数据的时候,可以在这个路由中created钩子函数中监听

    window.addEventListener('setItem', ()=> {
        this.newVal = sessionStorage.getItem('changeData');
    })
  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/yanyanliu/p/12856124.html
Copyright © 2011-2022 走看看