根据vue中的路线改变颜色

change color depending on route in vue

我需要根据路线或路线道具更改css颜色

例如: 如果我去主页 header 需要是红色的,如果我去关于页面 header 需要是绿色的

我在我的 router.js 中尝试过使用路由道具,但后来我无法在 header 组件中访问它们。

route.js

path: '/home',
    component: () => import('layouts/MainTemplate.vue'),
    children: [
      {
        path: '',
        name: 'home',
        css: 'red',
        component: () => import('pages/home')
      }
    ]

在我的组件中,我使用以下内容

  props: ['css']

并显示路线 css

{{ css }}

我如何使用路由道具来做到这一点,并且我的 header 组件可以接收它,如果我正在访问,例如回家?

update,示例我可以传递给如下属性:

navbarCSS: {
        '/': Home: {
          image: url,
          style: #ddd
        }
      },

我不确定 css 是否是 vue-router 中受支持的密钥。

因此,您最好像这样直接在相关的导航栏组件上执行此操作

<template>
  <div id="app">
    <div id="nav">
      <div :style="{ color: navbarColors[$route.path] }">Custom text in the navbar</div>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
  data() {
    return {
      navbarColors: {
        '/': 'red',
        '/about': 'blue',
      },
    }
  },
}
</script>

此处,div 将在 redblue 之间切换,具体取决于您是在根页面还是关于页面。
这是一个 github 回购示例:https://github.com/kissu/so-vue-route-color(几乎是默认的 vue2 设置,但以防万一)