VUE跳转时清空原有背景图

看了很多回答感觉都没说到点子上。

Vue 的路由切换通常是通过更新 router-view 中的内容,而不会销毁根组件 App.vue,除非手动做一些额外处理。

解决方法:

  1. 监听路由变化,动态更新背景图: 使用 watch 监听 $route 对象的变化,当路由变化时动态更新背景图。这样可以确保每次切换路由时背景图都能更新或者清除。

  2. 在路由变化时手动清除背景图: 可以在 beforeRouteLeavewatch 中清除背景图样式,避免它一直存在。

    <script>
    export default {
      name: 'App',
      data() {
        return {
          activeIndex: '1',
          activeIndex2: '1'
        };
      },
      methods: {
        handleSelect(key, keyPath) {
          console.log(key, keyPath);
        },
        setBackgroundImage() {
          const appElement = document.querySelector('#app');
          // 设置背景图样式
          appElement.style.position = 'absolute';
          appElement.style.top = '0';
          appElement.style.left = '0';
          appElement.style.width = '100%';
          appElement.style.height = '100%';
          appElement.style.background = `url(${require("../static/onePiece/lbk1.jpg")}) center/cover no-repeat`;
          appElement.style.opacity = '0.75';
          appElement.style.backgroundSize = '70% 140%';
          appElement.style.zIndex = '-1';
        },
        clearBackgroundImage() {
          const appElement = document.querySelector('#app');
          // 清除背景图样式
          appElement.style.background = '';
          appElement.style.opacity = '';
          appElement.style.backgroundSize = '';
          appElement.style.zIndex = '';
        }
      },
      mounted() {
        this.setBackgroundImage();
      },
      beforeDestroy() {
        this.clearBackgroundImage();
      },
      watch: {
        '$route'(to, from) {
          // 路由变化时清除背景图
          if (from.path === '/' && to.path !== '/') {
            this.clearBackgroundImage(); // 切换到其他路由时清除背景图
          } else {
            this.setBackgroundImage(); // 进入首页时重新设置背景图
          }
        }
      }
    };
    </script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值