I'm new in Vue and I have a problem with conditional rendering of a class managed by a child component and a page
When I load a page I have two sections, a component (navbar) and the page (in my case Home). By adding or not a specific class I would like the navbar in transparent, only when it is loaded on the Home page.
So I wrote this part in the navbar template:
<navbar class="normalclass" :class={transparent:istransparent}>Something</navbar>
JS:
export default {
name: 'Navbar',
data() {
return {
istransparent:false, // By default is false
}
}
}
In the views Home.vue I have instead inserted this code:
import { ref } from 'vue'
export default {
name: 'Home',
setup () {
const istransparent = ref(true)
return {
istransparent
}
}}
// I also tried to insert just this code but it doesn't change the result.
setup () {
return {
istransparent:true
}
}
In App.vue I have this part of the template that manages the rendering of the application
<Navbar />
<router-view />
<Footer />
I didn't understand exactly where I am wrong and what would be the best solution to do what I need.
I ask those who have more experience than me for help.
########## EDIT #########
Ok, I solved the problem with a different approach.
Instead of using a variable that is to be read in individual components (or in this case view), such as home.vue
I used vue-router to find out what page I was on. So since I want the transparent header only in the home, in the Navbar.vue component I have added this code to say that if I am in home then the variable is true, so I add the classes I need. Here the code used:
In navbar.vue:
<navbar class="normalclass" :class=
{transparent:isHome}>Something</navbar>
JS:
export default {
name: 'Navbar',
computed: {
isHome() {
return this.$route.name == 'Home' // Check if router name is 'Home'
}
}
}
}
I don't know if that's the best approach, but it works and feels stable, with very little code. I share it with you for the sake of knowledge.