【问题标题】:Change navigation component depending on what page user is on根据用户所在的页面更改导航组件
【发布时间】:2020-04-23 06:25:48
【问题描述】:

我在 vue 应用中使用透明导航栏。目的是根据用户所在的页面有不同的颜色链接。我正在使用vue-router 和一个单独的导航栏(导航)组件。

我对不同的页面有不同的背景颜色,例如主页有深灰色背景,而联系页面有白色背景,导航栏是固定的,所以我希望有一个深色的导航栏链接当背景为页面很轻,反之亦然。

这是在主页和联系页面上使用组件的方式

Home
 -navbar
 -hero
 -content
 -footer

Contact
 -navbar
 -contact form
 -footer

那么,有没有办法告诉导航栏在联系页面和主页上具有不同的链接颜色?

【问题讨论】:

  • 您能帮我理解更改链接颜色的意思吗?您只是想要一种方法来突出显示与用户当前所在路线相对应的链接吗?
  • @SerShubham 我对不同的页面有不同的背景颜色,例如主页有深灰色背景,而联系页面有白色背景,导航栏是固定的,所以我想要一个深色的页面背景较浅时的彩色导航栏链接,反之亦然
  • 啊。我明白。让我帮你解决:)

标签: javascript vue.js


【解决方案1】:

如果您使用vue-router,则可以从变量this.$route.path 访问用户当前所在的路线。例如,如果您的用户在 Home 路由上,则变量中的值可能是:/home

您可以使用它来动态更改导航栏的颜色:

//in your navbar.vue (navbar component)

<template>
   <div v-bind:class="{color: navBarColor}">
   </div>
</template>


<script>
export default {
   computed: {
      navBarColor() {
         if (this.$route.path === "/home") { // if it is a dark route
            return "#fff"; // basically any light color you want
         }
         return "#000"; // the dark color of your choice.
      }
   }
}
</script>

现在应该可以了。展望未来,我建议使用 vue 路由器中允许的 meta 键。您可以使用它为每个路由设置自定义元字段。

检查:https://router.vuejs.org/guide/advanced/meta.html

您的组件将如下所示:

//router.vue

const router = new VueRouter({
  routes: [
    {
      path: '/home', //the one with the dark background
      component: Home,
      meta: { navBarColor: '#fff' }
    }
  ]
});

// navbar.vue


<template>
   <div v-bind:class="{color: navBarColor}">
   </div>
</template>


<script>
export default {
   computed: {
      navBarColor() {
        return this.$route.meta.navBarColor
      }
   }
}
</script>

这两种方法中的任何一种都可以帮助你:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多