javascript - 根据用户所在的页面更改导航组件

标签 javascript vue.js

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

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

主页和联系页面的组件是这样使用的

Home
 -navbar
 -hero
 -content
 -footer

Contact
 -navbar
 -contact form
 -footer

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

最佳答案

如果您使用的是 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>

这应该暂时有效。展望 future ,我建议使用 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>

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

关于javascript - 根据用户所在的页面更改导航组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599753/

相关文章:

javascript - 鼠标悬停时更改字体颜色

javascript - VueJS : Issue with scoped slots and IE11

vue.js - 在VueJS中获取音频标签MP3

javascript - 数据不会在 vue js 中更新

javascript - async.waterfall 和 async.series 有什么区别

javascript - 在多次出现的项目中,仅删除第二个

javascript - 如何在nativescript-texttospeech中使用完成的回调函数?

javascript - 无法在Vue中使用$off并在eventbus中传递参数

javascript - 我如何将数据存储在可从任何地方访问的 nextjs 中

javascript - 随机图像高度不起作用?