有時候有些組件須要全局設置body背景,有些不須要在組件中設置就好了css
1. 全局設置能夠是html,body,這裏你們能夠試一下,這兩個只要其中一個設置了background,另外一個的背景就會失效。html
2. 咱們須要進入組件的時候使用鉤子函數beforeRouteEnter,設置body背景;函數
3. 離開組件以前beforeRouteLeave 清楚到body背景;ui
下面附上相應代碼:this
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() },}