![](/img/trans.png)
[英]how to change onlick event of a button depending on what page user is on
[英]Change navigation component depending on what page user is on
我在 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>
这应该暂时有效。 展望未来,我建议使用 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>
这两种方法中的任何一种都应该可以帮助您:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.