![](/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.