Home > Net >  nuxt 3 triggers changes from other components
nuxt 3 triggers changes from other components

Time:01-16

I have a question regarding triggering other components in nuxt 3. In nuxt 2 I can use $root.$refs to trigger components, but what about nuxt 3?

Example : in componentA I have a button that triggers a popup

<template>
  <button @click="openModal">Open</button>
  <div appear :show="isOpen">
    <component-b />
    test
  </div>
</template>
<script setup>
const isOpen = ref(false);

function openModal() {
  isOpen.value = true;
}
</script>

in componentB.vue I have a close button for popup in componentA

<button type="button" @click="closeModal">Close</button>

My goal is when the button from component B is clicked it can trigger the popup from component A to close.

CodePudding user response:

You could use an emit to do so.

In your component B, define an emit like:

// Component B
<template>
  <button type="button" @click="emit('close')">Close</button>
</template>

<script setup lang="ts">
const emit = defineEmits(['close'])
</script>

You can use this emit from your Component A to close the modal.

// Component A
<template>
  <button @click="openModal">Open</button>
  <div appear :show="isOpen">
    <component-b @close="isOpen = false" />
    test
  </div>
</template>
<script setup>
const isOpen = ref(false);

function openModal() {
  isOpen.value = true;
}
</script>
  • Related