同样适用于模态组件:
<!-- Modal component with Vue-Query --><script setup>import GridLoader from 'vue-spinner/src/GridLoader.vue'import { useQuery } from "vue-query";const props = defineProps({productId: {type: String,required: true,},});const emit = defineEmits(["close"]);async function fetchProduct() {return await fetch(`https://dummyjson.com/products/${props.productId}`).then((res) => res.json());}const { isLoading, data: product } = useQuery(["product", props.productId],fetchProduct);</script><template><div class="modal"><div class="modal__content" v-if="isLoading"><GridLoader /></div><div class="modal__content" v-else-if="product">// modal content omitted</div></div><div class="modal-overlay" @click="emit('close')"></div></template>- useQuery 返回名为 data 的响应,如果我们想要重命名它,我们可以使用es6的解构方式,如下 const { data: product } = useQuery(...) 当在同一页面进行多次查询时,这也非常有用 。
- 由于同一功能将用于所有产品,因此简单的字符串标识符将无法工作 。我们还需要提供产品id ["product", props.productId]

文章插图

文章插图
默认情况下,缓存数据被视为过时的 。当以下情况发生时,它们会自动在后台重新获取:
- 查询挂载的新实例
- 窗口被重新聚焦
- 网络已重新连接
- 该查询可选择配置为重新获取间隔
添加错误处理到目前为止,我们的代码都坚信API调用不会失败 。但在实际应用中,情况并非总是如此 。错误处理应在 try-catch块中实现,并需要一些额外的变量来处理错误状态 。幸运的是,vue-query 提供了一种更直观的方式,通过提供 isError 和 error 变量 。
<script setup>import { useQuery } from "vue-query";function fetchData() {// Make api call here}const { data, isError, error } = useQuery("uniqueKey",fetchData);</script><template>{{ data }}<template v-if="isError">An error has occurred: {{ error }}</template></template>总结总的来说,Vue Query通过用几行直观的Vue Query逻辑替换复杂的样板代码,简化了数据获取 。这提高了可维护性,并允许无缝地连接新的服务器数据源 。直接的影响是应用程序运行更快、反应更灵敏,可能节省带宽并提高内存性能 。此外,我们没有提到的一些高级功能,如预取、分页查询、依赖查询等,提供了更大的灵活性,应该能满足您的所有需求 。
如果你正在开发中到大型的应用程序,你绝对应该考虑将 Vue Query 添加到你的代码库中 。
【使用Vue Query进行高级数据获取】
推荐阅读
- Win10自动修复失败解决指南
- 怎么使用卷发棒 怎么使用卷发棒卷头发视频
- 电压表的使用 电压表的使用视频
- 电压表的使用方法 直流电压表的使用方法
- 德尔玛加湿器使用方法 加湿器使用方法
- 面包机的使用方法视频教程美的 面包机的使用方法
- 茶树精油的使用方法 茶树精油正确使用方法大全
- 华为新移动电源 华为移动电源首次使用注意事项
- Dynalang——一种使用语言学习世界模型的AI新技术
- MySQL算术运算符使用详解
