在 vue router 中更改 body 样式 [英] Changing body styles in vue router
问题描述
我正在使用带有两个页面的 Vue 路由器:
让路线= [{小路: '/',组件:需要('./components/HomeView.vue')},{路径:'/介绍',组件:需要('./components/IntroView.vue')}]
这很好用,只是我的每个组件都有不同的主体样式:
HomeView.vue:
<p>这是主页!</p>模板><脚本>导出默认{}<风格>身体 {背景:红色;}</风格>
IntroView.vue:
<div><h1>简介</h1>
模板><脚本>导出默认{}<风格>身体 {背景:粉红色;}</风格>
我的目标是让这两个页面具有不同的背景样式(最终在它们之间进行过渡).但是在我去home
路线(带有red
背景)的那一刻,然后点击intro
路线,背景颜色保持red
(我希望它变成pink
).
index.html:
<div id="应用程序"><router-link to="/"精确>主页</router-link><router-link to="/intro">介绍</router-link><路由器视图></路由器视图>
<script src="/dist/build.js"></script>
我使用 生命周期钩子 beforeCreate
和一个全局样式表.在 global.css
中:
body.home {背景:红色;}body.intro {背景:粉红色;}
在HomeView.vue
的部分:
出口默认{之前创建:函数(){document.body.className = 'home';}}
与IntroView.vue
类似.
I'm using Vue router with two pages:
let routes = [
{
path: '/',
component: require('./components/HomeView.vue')
},
{
path: '/intro',
component: require('./components/IntroView.vue')
}
]
This works fine, except that each of my components has different body styling:
HomeView.vue:
<template>
<p>This is the home page!</p>
</template>
<script>
export default {
}
</script>
<style>
body {
background: red;
}
</style>
IntroView.vue:
<template>
<div>
<h1>Introduction</h1>
</div>
</template>
<script>
export default {
}
</script>
<style>
body {
background: pink;
}
</style>
My goal is to have these two pages have different background styles (eventually with a transition between them). But at the moment when I go to the home
route (with the red
background), then click the intro
route, the background colour stays red
(I want it to change to pink
).
Edit: index.html:
<body>
<div id="app">
<router-link to="/" exact>Home</router-link>
<router-link to="/intro">Introduction</router-link>
<router-view></router-view>
</div>
<script src="/dist/build.js"></script>
</body>
I got it working with the lifecycle hook beforeCreate
and a global stylesheet. In global.css
:
body.home {
background: red;
}
body.intro {
background: pink;
}
In the <script>
section of HomeView.vue
:
export default {
beforeCreate: function() {
document.body.className = 'home';
}
}
And similar in IntroView.vue
.
这篇关于在 vue router 中更改 body 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!