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={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=
{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.
CodePudding user response:
You will need some kind of global state. You can use Pinia, Vuex or create a file for your global state:
// store.js
import { reactive } from 'vue'
export const store = reactive({
isTransparent: false
})
then in Home.vue
component set state:
import { store } from './store.js'
export default {
mounted() {
store.isTransparent = true
},
unmounted() {
store.isTransparent = false
}
}
so in navbar.vue
you check global state:
<nav :>
Something
{{ store.isTransparent }}
</nav>
<script>
import { store } from "../store.js";
export default {
name: "Navbars",
data() {
return {
store,
};
},
};
CodePudding user response:
Solved, look my edit part of question.