weixin_58412143 2022-03-30 09:20 采纳率: 90.9%
浏览 79
已结题

vue 切换组件后取不到缓存内容

情景:有两个tab页A,B,有个共用的头部组件可以实现A,B中echarts的换肤。
问题:现在的情况是单独在A或B里换肤是可以实现的,但是在切换A,B时换肤效果就没了(就是A里实现换肤后,切换到B中没有实现,再从B中返回到A时,A的效果也没了)A,B是两个组件,换肤功能是在他们的父组件里(父组件>中间组件1>中间组件2>A组件)
1、父组件

//切换到A
      homeChange() {
        if (this.themetype == null) {
           // this.themetype = 'dark'
         } else {
           this.resetSetItem('setThemetype', this.themetype);//这里打印this.themetype是对的
           }
      },
      //切换到B
      hjChange() {
        if (this.themetype == null) {
          // this.themetype = 'dark'
        } else {
          this.resetSetItem('setThemetype', this.themetype);//这里打印this.themetype是对的
          }
        },
     //换肤
change(theme) {
            if (this.themetype == 'dark') {
              document.documentElement.setAttribute("data-theme", 'light');
              this.themetype = 'light'
              console.log('改变为白色主题')
            } else {
              document.documentElement.setAttribute("data-theme", 'dark');
              this.themetype = 'dark'
              console.log('改变为深色主题')
            }
            // sessionStorage.setItem('setThemetype', this.themetype);//ok
            this.resetSetItem('setThemetype', this.themetype);//缓存当前主题
          },

2、A组件

    created() {
      window.addEventListener('setItem', () => {
        this.type = sessionStorage.getItem('setThemetype');
        if (this.type == 'light') {
          this.$set(this.options.toolbox.feature.dataView, 'backgroundColor', "#F1F0FE")
        } else if (this.type == 'dark') {
          this.$set(this.options.toolbox.feature.dataView, 'backgroundColor', "RGBA(8, 24, 54, 1)")
        }
      })
    },
   beforeDestroy() {
      //清除session
      sessionStorage.removeItem('setThemetype');
    },
  • 写回答

2条回答 默认 最新

  • rock.dai 2022-03-30 10:07
    关注

    这种情况你期望的是全局换肤吧?
    可以使用Vuex作为状态管理库,如果是小组件也可以是使用楼上说的keep-alive。因为你现在的代码是每个页面各自监听,当页面切换后,换肤的效果自然也就没有了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月7日
  • 已采纳回答 3月30日
  • 创建了问题 3月30日

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题