Notification texts go here Contact Us Buy Now!

Why does the reactivity of VUE 3 CompositionAPI not work?

The issue with reactivity not working between unrelated components when using a function like useModal is that each time you import useModal in a different component, you're creating a new instance of the isShowModal ref.

When you call openModal in one component, it updates the isShowModal ref in that specific instance of useModal, but it doesn't affect the isShowModal ref in the other component.

To share the same reactivity instance between components, you can use a shared state management solution like Vuex or provide and inject.

Alternatively, you can export the isShowModal ref directly from ModalsController.js and import it in both components. This way, they will share the same reactivity instance:

ModalsController.js:
import { ref } from 'vue';
export const isShowModal = ref(false);
export const openModal = () => {
  isShowModal.value = true;
};
export const closeModal = () => {
  isShowModal.value = false;
};
Header.vue:
<template>
  <button @click="openModal">OpenModal</button>
  {{ isShowModal }} 
  <button @click="closeModal">CloseModal</button>
</template>

<script setup>
import { isShowModal, openModal, closeModal } from "./ModalsController.js";
</script>
Modal.vue:
<template>
  <div v-if="isShowModal"> Modal window </div>
</template>

<script setup>
import { isShowModal } from "./ModalsController.js";
</script>

This way, both components will share the same isShowModal reactivity instance, and calling openModal or closeModal in one component will affect the other component as well.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.