Glu*_*ear 18 javascript vue.js vue-router vue-loader
我正在使用两页的Vue路由器:
let routes = [
{
path: '/',
component: require('./components/HomeView.vue')
},
{
path: '/intro',
component: require('./components/IntroView.vue')
}
]
Run Code Online (Sandbox Code Playgroud)
这很好,除了我的每个组件都有不同的主体样式:
HomeView.vue:
<template>
<p>This is the home page!</p>
</template>
<script>
export default {
}
</script>
<style>
body {
background: red;
}
</style>
Run Code Online (Sandbox Code Playgroud)
IntroView.vue:
<template>
<div>
<h1>Introduction</h1>
</div>
</template>
<script>
export default {
}
</script>
<style>
body {
background: pink;
}
</style>
Run Code Online (Sandbox Code Playgroud)
我的目标是让这两个页面具有不同的背景样式(最终在它们之间进行过渡).但是当我去home路线(有red背景)的时候,然后点击intro路线,背景颜色保持不变red(我希望它改变为pink).
编辑: 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>
Run Code Online (Sandbox Code Playgroud)
Glu*_*ear 32
我使用了生命周期钩子 beforeCreate和全局样式表.在global.css:
body.home {
background: red;
}
body.intro {
background: pink;
}
Run Code Online (Sandbox Code Playgroud)
在以下<script>部分HomeView.vue:
export default {
beforeCreate: function() {
document.body.className = 'home';
}
}
Run Code Online (Sandbox Code Playgroud)
和类似的IntroView.vue.
watch: {
$route: {
handler (to, from) {
const body = document.getElementsByTagName('body')[0];
if (from !== undefined) {
body.classList.remove('page--' + from.name.toLowerCase());
}
body.classList.add('page--' + to.name.toLowerCase());
},
immediate: true,
}
},
Run Code Online (Sandbox Code Playgroud)
另一个相当简单的解决方案,将其添加到您的基本 App.vue 文件中。to.name 可以替换为 to.meta.class 或类似的更具体的东西。这是一个很好的做一次,但它可以永远工作类型解决方案。
| 归档时间: |
|
| 查看次数: |
14973 次 |
| 最近记录: |