码迷,mamicode.com
首页 > Web开发 > 详细

vue - 设置全局html背景

时间:2019-05-17 18:12:46      阅读:839      评论:0      收藏:0      [点我收藏+]

标签:全局   ext   query   route   return   png   ima   log   获取   

需求

  有时候有些组件需要全局设置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()
  },
}

 

vue - 设置全局html背景

标签:全局   ext   query   route   return   png   ima   log   获取   

原文地址:https://www.cnblogs.com/mmzuo-798/p/10882789.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!