vue - 设置全局html背景


需求

  有时候有些组件需要全局设置body背景,有些不需要在组件中设置就行了

解决思路

  1. 全局设置可以是html,body,这里大家可以试一下,这两个只要其中一个设置了background,另一个的背景就会失效。

  2. 我们需要进入组件的时候使用钩子函数beforeRouteEnter,设置body背景;

  3. 离开组件之前beforeRouteLeave 清楚到body背景;

下面附上相应代码:

 
 
export default {
  name: 'login',
  data() {
    return {
      bgUrl: require("@/assets/images/home/bg_regLogin.png"),
    }
  },
   methods: {
  beforeRouteEnter (to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当钩子执行前,组件实例还没被创建
    next(vm => { document.querySelector('html').style.cssText = ` background: url(${vm.bgUrl}) center no-repeat; background-size: cover; background-attachment: fixed; ` }) }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    document.querySelector('html').style.cssText = `background: #f4f6f9;` next() },
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM