[Vue] Sharing State
📄 /composables/use-promise.js
import { ref } from "@vue/composition-api";
export default function usePromise(fn) { // fn is the actual API call
const results = ref(null);
const loading = ref(false);
const error = ref(null);
const createPromise = async (...args) => { // Args is where we send in searchInput
loading.value = true;
error.value = null;
results.value = null;
try {
results.value = await fn(...args); // Passing through the SearchInput
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
};
return { results, loading, error, createPromise };
}
Notice how this function holds the reactive references as well as a function that wraps the API call, along with any arguments that need to be passed into the API call. Now to use this code:
📄 /src/App.vue
<template>
<div>
Search for <input v-model="searchInput" />
<div>
<p>Loading: {{ getEvents.loading }}</p>
<p>Error: {{ getEvents.error }}</p>
<p>Number of events: {{ getEvents.results }}</p>
</div>
</div>
</template>
<script>
import { ref, watch } from "@vue/composition-api";
import eventApi from "@/api/event.js";
import usePromise from "@/composables/use-promise";
export default {
setup() {
const searchInput = ref("");
const getEvents = usePromise(search =>
eventApi.getEventCount(search.value)
);
watch(searchInput, () => {
if (searchInput.value !== "") {
getEvents.createPromise(searchInput);
} else {
getEvents.results.value = null;
}
});
return { searchInput, getEvents };
}
};
</script>
分类:
Vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-11-29 [CSS3] Container query
2022-11-29 [Typescript] 121. Hard - IsPalindrome
2020-11-29 [Java Srping] @RestController and @Controller
2020-11-29 [Java Spring] Testing a view controller
2019-11-29 [Algorithm] BFS vs DFS
2017-11-29 [ES2017] Iterate over properties of an object with ES2017 Object.entries()
2016-11-29 [Elm] Installing and setting up Elm