'Why does the reactivity of VUE 3 CompositionAPI not work?

Please tell me why reactivity between unrelated components does not work:

ModalsController.js:

import { ref } from 'vue';
export const useModal = (init = false)=>{
  const isShowModal = ref(init);
  const openModal = () => {
    isShowModal.value = true;
  };
  
  const closeModal = () => {
    isShowModal.value = false;
  };
  return {
    isShowModal, openModal, closeModal
  }
}

Header.vue:

<template>
    
  <button @click="openModal">OpenModal</button>
 {{isShowModal}} 
    <button @click="closeModal">CloseModal</button>
</template>

<script setup>

import {useModal} from "./ModalsController.js";
const { isShowModal,openModal,closeModal } = useModal();
  
  

</script> 

Modal.vue:

<template>
 
  <div v-if="isShowModal"> Modal window </div>
  
</template>

<script setup>
 import {useModal} from "./ModalsController.js";
const {isShowModal} = useModal();

</script>  

And everything works if I create a simple variable instead of a function like this:

ModalsController.js:

import { ref } from 'vue';
export const isShowModal = ref(false);

and accordingly, I change it in the header. But this is very inconvenient because there are way more functions (switching, etc.) Thank you all in advance for your help. I put the code in the Playground for the test:

  1. Not a working (func)
  2. working (simple var)


Solution 1:[1]

The problem is useModal() creates a new ref() every time it's called. Each of your components calls useModal() to get the isShowModal ref, but each ref is a newly created one independent from each other.

To share the refs between components, move the ref creation outside of the useModal function definition:

import { ref } from 'vue';

const isShowModal = ref(false); ?

export const useModal = (init = false) => {
  // const isShowModal = ref(init); ? move this outside function
  ?
}

demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tony19