在 Vue 路由器中更改正文样式

新手上路,请多包涵

我正在使用带有两个页面的 Vue 路由器

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

这很好用,除了我的每个组件都有不同的主体样式:

主视图.vue:

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

<script>
    export default {

    }
</script>

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

介绍视图.vue:

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

<script>
    export default {

    }
</script>

<style>
    body {
        background: pink;
    }
</style>

我的目标是让这两个页面具有不同的背景样式(最终在它们之间进行过渡)。 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 (我希望它更改为 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>

原文由 GluePear 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 407
2 个回答

我让它与 生命周期挂钩 beforeCreate 和一个全局样式表一起工作。在 global.css

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

<script> 部分 HomeView.vue

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

IntroView.vue 类似。

原文由 GluePear 发布,翻译遵循 CC BY-SA 4.0 许可协议

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,
  }
},

另一个相当简单的解决方案,将它添加到您的基础 App.vue 文件中。 to.name 可以替换为 to.meta.class 或类似的更具体的东西。这是一个很好的一次性解决方案,但它永远有效。

原文由 Lomax 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题