Vue单独页面设置body

小知识 09-01 15:06

在一个Vue项目中,因需要会员中心设置不同的背景颜色,发现在最外层的DIV 设置样式背景颜色不行,单独把 body 设置在样式文件里,会影响到其它页面也不成功。由于SPA页面的特性,传统的设置 body 背景色的方法并不通用。后来想到通过vue的生命周期或者内部组件来解决。

解决方案:

一、vue的生命周期

<script>
export default {
  data() {
    return {
    }
  },
  //创建前设置
  beforeCreate () {
      document.querySelector('body').setAttribute('style', 'background-color:#efeff4;')
  },
  //销毁前清除
  beforeDestroy () {
      document.querySelector('body').removeAttribute('style')
  },
}
</script>

二、利用组件内的路由实现

<script>
export default {
  data() {
    return {
    }
  },
  // 组件内路由进入组件时
  beforeRouteEnter(to, from, next) {
    window.document.body.style.backgroundColor='#f2f3f8'
    next()
  },
  // 组件内路由离开组件时
  beforeRouteLeave(to, from, next) {
    window.document.body.style.backgroundColor=''
    next()
  }
}
</script>