I'm developing a Vue 3 application. I have 3 nested components: a button component, nested inside a navigation component, which is nested inside a content component.
This button should toggle the value of the Boolean variable isVisible
within the grandparent component Main.vue
(content component).
In Sun componentMyButton.vue
:
<template> <button @click="handleClick" class="btn btn-sm btn-success"> {{ label }} </button> </template> <script> export default { name: 'MyButton', props: { label: String, isVisible: Boolean }, emits: [ 'toggleVisibility', ], methods: { handleClick() { this.$emit('toggleVisibility') } } } </script>
In parent component Navigation.vue
:
<template> <div class="navigation"> <MyButton :label='"Toggle content"' :isVisible=false @toggleVisibility="$emit('toggleVisibility')" /> </div> </template> <script> import MyButton from './MyButton' export default { emits: [ 'toggleVisibility', ], } </script>
In grandparent componentMain.vue
:
<template> <div class="main"> <Navigation /> <div v-if="isVisible" class="content"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> </div> </template> <script> import Navigation from './Ui/Navigation' export default { name: 'Main', components: { Navigation }, props: { title: String, tagline: String, }, data() { return { isVisible: false, } }, methods: { toggleVisibility() { console.log('ok'); this.isVisible = !this.isVisible; } } } </script>
As shown above, I tried firing upwards, one component at a time.
For reasons I can't understand, this doesn't work.
#1 You did not declare the
MyButton
component in the parentNavigation
component.Add it to
export default {}
#2 You are not listening to events in the grandparent
Main
component.Replace the line
<Navigation />
with:P.S: For custom events, prefer using
kebab-case
. Just a best practice.toggle-visiblity
instead oftoggleVisibility