Answer the question
In order to leave comments, you need to log in
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
}
}
<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>
<template>
<div v-if="isShowModal"> Modal window </div>
</template>
<script setup>
import {useModal} from "./ModalsController.js";
const {isShowModal} = useModal();
</script>
import { ref } from 'vue';
export const isShowModal = ref(false);
Answer the question
In order to leave comments, you need to log in
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
, closeModal
variables 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.js
you need to design it as a class, and pass an instance * of this class to the component as a prop.
Now, modal-state.js
in 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 questionAsk a Question
731 491 924 answers to any question