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:
import { ref } from 'vue'; export const isShowModal = ref(false); export const openModal = () => { isShowModal.value = true; }; export const closeModal = () => { isShowModal.value = false; };
<template> <button @click="openModal">OpenModal</button> {{ isShowModal }} <button @click="closeModal">CloseModal</button> </template> <script setup> import { isShowModal, openModal, closeModal } from "./ModalsController.js"; </script>
<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.