Answer the question
In order to leave comments, you need to log in
How to communicate between components through Promise?
How to return the result of a promise (resolve / reject) from one component after sending a request inside it, so that in another component it can be processed through then? In this case, the components may not be nearby and may not have a common parent.
Answer the question
In order to leave comments, you need to log in
How to return the result of the promise (resolve / reject) from one component after sending the request inside it, so that in another component to process it through then
In this case, the components may not be nearby and may not have a common parent.
Isn't it better to have a function that will make a request and process the result and write it to a reactive variable?
One component calls this function.
Another component uses this reactive variable for its own purposes. ("Depends on her")
Demo: https://sfc.vuejs.org/#eyJBc...
core.js
import {ref, readonly} from "vue";
const todo = ref(null);
const todoId = ref(1);
export async function fetchTodo() {
const resp = await fetch("https://jsonplaceholder.typicode.com/todos/" + todoId.value++);
todo.value = await resp.json();
};
// Using of `readonly` is optional, I use it just in case.
// You can just export `todoId`, `todo` (above) as is.
const _todoId = readonly(todoId);
const _todo = readonly(todo);
export {
_todoId as todoId,
_todo as todo
};
<template>
<Button/>
<div v-if="todo">
{{todo}}
</div>
</template>
<script setup>
import Button from "./Button.vue";
import {todo} from "./core.js";
</script>
<template>
<button @click="fetchTodo">fetchTodo({{todoId}})</button>
</template>
<script setup>
import {fetchTodo, todoId} from "./core.js";
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question