N
N
Nina Fineberg2022-02-17 03:16:20
Vue.js
Nina Fineberg, 2022-02-17 03:16:20

Why doesn't VUE3 CompositionAPI reactivity 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 not very convenient, because. there are many more functions (switching, etc.)
Thanks in advance to everyone for the help, here I posted it in the Playground for testing:
Not working version
Working version

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GrayHorse, 2022-02-17
@NinaFFF

Firstly, the code could have been formatted somehow: the first option , the second .
It doesn't work, because each component has useModal()its own private isShowModal, openModal, closeModalvariables when it is exported.
If you don’t try to make something like React Hooks out of Vue, then here’s a working option.
(Based on the fact that the component will be in one instance.)
For the sake of formality: if the component is planned to be used more than once, then modal-state.jsyou need to design it as a class, and pass an instance * of this class to the component as a prop.
Now, modal-state.jsin fact, a singleton.

* Which will still need to be stored somewhere (in some js file) if access from several components is planned.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question