本文介绍了在Vue Router中更改身体样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个页面上使用 Vue路由器:

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>

我的目标是使这两个页面具有不同的背景样式(最终在它们之间进行过渡).但是,当我转到 home 路线(具有 red 背景),然后单击 intro 路线时,背景颜色保持 red (我希望将其更改为 pink ).

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).

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>

推荐答案

我使用生命周期挂钩 beforeCreate 和全局样式表.在 global.css 中:

I got it working with the lifecycle hook beforeCreate and a global stylesheet. In global.css:

body.home {
    background: red;
}
body.intro {
    background: pink;
}

HomeView.vue < script> 部分中:

export default {
    beforeCreate: function() {
        document.body.className = 'home';
    }
}

IntroView.vue 中的类似.

这篇关于在Vue Router中更改身体样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:25