Home  >  Q&A  >  body text

How do I change the value of a boolean variable in a grandchild component in this Vue 3 application?

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>

question

As shown above, I tried firing upwards, one component at a time.

For reasons I can't understand, this doesn't work.

question

  1. Where is my mistake?
  2. What is the shortest possible solution?

P粉667649253P粉667649253240 days ago316

reply all(1)I'll reply

  • P粉344355715

    P粉3443557152024-02-22 10:12:07

    #1 You did not declare the MyButton component in the parent Navigation component.
    Add it to export default {}

    components: {
       MyButton
    },

    #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 of toggleVisibility

    reply
    0
  • Cancelreply