Reputation: 73
I am trying to change the background and text color of my navbar component depending on what page I am on in order to remove contrasting colors with the current pages background. Effectively wanting a light and dark theme variant for the TopNav component that is triggered by what page we are currently on.
My nav bar and page template is as below:
<template>
<v-app>
<TopNav /> ------> This is the navbar component whos css i want to alter
<v-content>
<router-view></router-view> -----> Depending on what the current page injected is.
</v-content>
<Footer />
</v-app>
</template>
Using <style>
tags without the scoped
attribute work on changing the navbar background but unfortunately it does not revert back after navigating to another page.
Upvotes: 0
Views: 1112
Reputation: 360
Changing state of a component from a sibling level or child level component is really an anti-pattern.
Your best bet is going to be using a well established pattern to get the functionality you're after.
One way to do this is to bring in Vuex, and place your light/dark mode in the Vuex store (shared application level state management)
Then, you could setup your TopNav component to bind to a value in Vuex state (this.$store.state.darkMode
for example)
Then, from anywhere in the application, you could commit a mutation to specify light mode, dark mode, toggle, etc...
Or, if you want it to always be route-specific (kinda sounds like this is the case) then you can setup your route definition something like this:
const routes = [
{
path: '/light-component',
name: 'LightComponent',
component: () => LightComponent,
meta: {
darkMode: false,
},
},
{
path: '/dark-component',
name: 'DarkComponent',
component: () => DarkComponent,
meta: {
darkMode: true,
},
},
];
Then, in any component (your TopNav component for example) you could do something like:
<template>
<div :class="darkModeClass">
...
// inside <script> ...
computed: {
darkModeClass() {
return { dark: !!this.$route.meta?.darkMode };
}
}
...
<style scoped>
.dark {
/* css styles for dark mode */
}
</style>
Upvotes: 1