看了很多回答感觉都没说到点子上。
Vue 的路由切换通常是通过更新 router-view
中的内容,而不会销毁根组件 App.vue
,除非手动做一些额外处理。
解决方法:
-
监听路由变化,动态更新背景图: 使用
watch
监听$route
对象的变化,当路由变化时动态更新背景图。这样可以确保每次切换路由时背景图都能更新或者清除。 -
在路由变化时手动清除背景图: 可以在
beforeRouteLeave
或watch
中清除背景图样式,避免它一直存在。<script> export default { name: 'App', data() { return { activeIndex: '1', activeIndex2: '1' }; }, methods: { handleSelect(key, keyPath) { console.log(key, keyPath); }, setBackgroundImage() { const appElement = document.querySelector('#app'); // 设置背景图样式 appElement.style.position = 'absolute'; appElement.style.top = '0'; appElement.style.left = '0'; appElement.style.width = '100%'; appElement.style.height = '100%'; appElement.style.background = `url(${require("../static/onePiece/lbk1.jpg")}) center/cover no-repeat`; appElement.style.opacity = '0.75'; appElement.style.backgroundSize = '70% 140%'; appElement.style.zIndex = '-1'; }, clearBackgroundImage() { const appElement = document.querySelector('#app'); // 清除背景图样式 appElement.style.background = ''; appElement.style.opacity = ''; appElement.style.backgroundSize = ''; appElement.style.zIndex = ''; } }, mounted() { this.setBackgroundImage(); }, beforeDestroy() { this.clearBackgroundImage(); }, watch: { '$route'(to, from) { // 路由变化时清除背景图 if (from.path === '/' && to.path !== '/') { this.clearBackgroundImage(); // 切换到其他路由时清除背景图 } else { this.setBackgroundImage(); // 进入首页时重新设置背景图 } } } }; </script>