使用Vue Query进行高级数据获取

boyanx1个月前技术教程4

构建现代大规模应用程序最具挑战性的方面之一是数据获取。加载和错误状态、分页、过滤、排序、缓存等许多功能可能会增加复杂性,并经常使应用程序充满大量的样板代码。

这就是 Vue Query 库的用途所在。它使用声明式语法处理和简化数据获取,并在幕后为我们处理所有那些重复的任务。

理解 Vue Query

Vue Query 并不是 Axiosfetch 的替代品。它是在它们之上的一个抽象层。

管理服务器状态时面临的挑战与管理客户端状态不同,而且更为复杂。我们需要解决的问题包括:

  • 缓存...(可能是编程中最难的事情)
  • 将对相同数据的多个请求进行去重,合并为一个请求
  • 在后台更新过时的数据
  • 了解何时数据过时
  • 尽快反映数据的更新情况
  • 像分页和懒加载这样的性能优化
  • 管理服务器状态的内存和垃圾回收
  • 使用结构共享来记忆化查询结果

Vue Query真棒,因为它为我们隐藏了所有这些复杂性。它默认基于最佳实践进行配置,但也提供了一种方法来更改这个配置(如果需要的话)。

基本示例使用

通过构建以下简单的应用程序来展示这个图书馆。

在页面级别上,我们需要获取所有产品,将它们展示在一个表格中,并有一些简单的额外逻辑来选择其中的一个。

<!-- Page component without Vue-Query -->
<script setup>
import { ref } from "vue";
import BoringTable from "@/components/BoringTable.vue";
import ProductModal from "@/components/ProductModal.vue";

const data = ref();
const loading = ref(false);

async function fetchData() {
  loading.value = true;
  const response = await fetch(
    `https://dummyjson.com/products?limit=10`
  ).then((res) => res.json());
  data.value = response.products;
  loading.value = false;
}

fetchData();

const selectedProduct = ref();

function onSelect(item) {
  selectedProduct.value = item;
}
</script>

<template>
  <div class="container">
    <ProductModal
      v-if="selectedProduct"
      :product-id="selectedProduct.id"
      @close="selectedProduct = null"
    />
    <BoringTable :items="data" v-if="!loading" @select="onSelect" />
  </div>
</template>

在选择产品的情况下,我们会显示一个模态框,并在显示加载状态时获取额外的产品信息。

<!-- Modal component without Vue-Query -->
<script setup>
import { ref } from "vue";
import GridLoader from 'vue-spinner/src/GridLoader.vue'

const props = defineProps({
  productId: {
    type: String,
    required: true,
  },
});

const emit = defineEmits(["close"]);

const product = ref();
const loading = ref(false);

async function fetchProduct() {
  loading.value = true;
  const response = await fetch(
    `https://dummyjson.com/products/${props.productId}`
  ).then((res) => res.json());
  product.value = response;
  loading.value = false;
}

fetchProduct();
</script>

<template>
  <div class="modal">
    <div class="modal__content" v-if="loading">
      <GridLoader />
    </div>
    <div class="modal__content" v-else-if="product">
      // modal content omitted
    </div>
  </div>
  <div class="modal-overlay" @click="emit('close')"></div>
</template>

添加 Vue Query

这个库预设了一些既激进又理智的默认设置。这意味着我们在基本使用时不需要做太多操作。

<script setup>
import { useQuery } from "vue-query";

function fetchData() {
  // Make api call here
}

const { isLoading, data } = useQuery(
  "uniqueKey",
  fetchData
);
</script>

<template>
  {{ isLoading }}
  {{ data }}
</template>

在上述例子中:

  • uniqueKey 是用于缓存的唯一标识符
  • fetchData 是一个函数,它返回一个带有API调用的 promise
  • isLoading 表示API调用是否已经完成
  • data 是对API调用的响应

我们将其融入到我们的例子中:

<!-- Page component with Vue-Query -->
<script setup>
import { ref } from "vue";
import { useQuery } from "vue-query";

import BoringTable from "@/components/BoringTable.vue";
import OptimisedProductModal from "@/components/OptimisedProductModal.vue";

async function fetchData() {
  return await fetch(`https://dummyjson.com/products?limit=10`).then((res) => res.json());
}

const { isLoading, data } = useQuery(
  "products",
  fetchData
);

const selectedProduct = ref();

function onSelect(item) {
  selectedProduct.value = item;
}
</script>

<template>
  <div class="container">
    <OptimisedProductModal
      v-if="selectedProduct"
      :product-id="selectedProduct.id"
      @close="selectedProduct = null"
    />
    <BoringTable :items="data.products" v-if="!isLoading" @select="onSelect" />
  </div>
</template>

现在,由于库已经处理了加载状态,所以获取函数已经简化。

同样适用于模态组件:

<!-- 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>
  1. useQuery 返回名为 data 的响应,如果我们想要重命名它,我们可以使用es6的解构方式,如下 const { data: product } = useQuery(...) 当在同一页面进行多次查询时,这也非常有用。
  2. 由于同一功能将用于所有产品,因此简单的字符串标识符将无法工作。我们还需要提供产品id ["product", props.productId]

我们并没有做太多事情,但我们从这个盒子里得到了很多。首先,即使在没有网络限制的情况下,当重新访问一个产品时,从缓存中得到的性能提升也是显而易见的。

默认情况下,缓存数据被视为过时的。当以下情况发生时,它们会自动在后台重新获取:

  • 查询挂载的新实例
  • 窗口被重新聚焦
  • 网络已重新连接
  • 该查询可选择配置为重新获取间隔

此外,失败的查询会在捕获并向用户界面显示错误之前,静默地重试3次,每次重试之间的延迟时间呈指数级增长。

添加错误处理

到目前为止,我们的代码都坚信API调用不会失败。但在实际应用中,情况并非总是如此。错误处理应在 try-catch块中实现,并需要一些额外的变量来处理错误状态。幸运的是,vue-query 提供了一种更直观的方式,通过提供 isErrorerror 变量。

<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 React Ts 等。

相关文章

新买的笔记本电脑,小白该如何操作?

直切主题,接下来这篇文章将为您介绍,小白入手笔记本的一些常见问题和避坑方法。开机连接电源,长按开机键笔记本出厂后第一次开机需要连接电源激活电池,然后才能开机,只需要插上电源然后长按开机键,就可以开机了...

前端如何搞监控总结篇

本文部分内容和截图内容都来自以下第五届前端早早聊大会分享 总结笔记本文是会议总结文章,可能会有点大乱炖的感觉。监控步骤:定制规范,埋点 > 采集 > 计算 > 分析数据埋点的业务价值...

联想Z6 Pro系统更新:新增双景Vlog模式/锁屏闪拍玩法

4月23日,联想正式发布旗下第二款骁龙855旗舰机型——联想Z6 Pro。该机型除了具备了高通骁龙855强劲的性能外,还搭载了名为“HYPER VIDEO”的影像系统,不管是拍照还是视频拍摄都有着新奇...

91那些大神,为啥不再使用爱剪辑

long long ago,机哥发过好几期关于 P 图的教程。用的呢,是谷歌家的 Snapseed,功能全,特效多,操作简单。来一波回顾。今天呢,就不玩 P 图,来点高端,也是机友一直期待的,剪辑视频...

微信小程序面试题整理

微信小程序 的官方文档https://developers.weixin.qq.com/miniprogram/dev/framework/quickstart/#小程序简介1 、如何获得用户的授权信...

7日衣橱丨被谭松韵种草了!早秋做个美少女

在本周的今天穿什么栏目,InStyle非常荣幸的邀请到了演员谭松韵,让我们一起听听她的时髦经!提到谭松韵,你想到的可能还是五年前《甄嬛传》中稚气可爱的淳贵人。毕竟是因为这个角色,她才开始逐渐走入观众们...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。