需求
有時候有些組件需要全局設置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() },
}
