我在 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/