在Vue Router中更改身体样式

JavaScript

A米亚

2020-03-12

我正在使用两页的Vue路由器

let routes = [
    {
        path: '/',
        component: require('./components/HomeView.vue')
    },
    {
        path: '/intro',
        component: require('./components/IntroView.vue')
    }
]

除了我的每个组件都有不同的身体样式之外,这都可以正常工作:

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

编辑: 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>

第1324篇《在Vue Router中更改身体样式》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
小胖Eva 2020.03.12

您可以在style元素中使用scoped属性。然后,样式将仅限于该vue文件。

HomeView.vue:

<template>
    <p>This is the home page!</p>
</template>

<script>
    export default {

    }
</script>

<style scoped>
    body {
        background: red;
    }
</style>

IntroView.vue:

<template>
    <div>
        <h1>Introduction</h1>
    </div>
</template>

<script>
    export default {

    }
</script>

<style scoped>
    body {
        background: pink;
    }
</style>
路易Itachi小小 2020.03.12

或者,您可以使用此

它允许使用vue-router控制您的页面正文类。遇到类似问题时写了这个。它也指单击组件时向主体添加类?

JinJin老丝 2020.03.12

您也可以使用afterEach钩子直接在路由器文件中执行此操作

mainRouter.afterEach((to) => {
    if (["dialogs", "snippets"].includes(to.name)) {
        document.body.style.backgroundColor = "#F7F7F7";
        // or document.body.classList.add(className);
    } else {
        document.body.style.backgroundColor = "#FFFFFF";
        // or document.body.classList.remove(className);
    }
});

afterEach 挂钩文件

to是一个路线对象,其中包含路线名称(如果已命名),路径等 。所有道具的文档

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android