微信搜索 【大迁世界】, 我会第一时间和你分享前端行业趋势,学习途径等等。
本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

快来免费体验ChatGpt plus版本的,我们出的钱 体验地址:https://chat.waixingyun.cn 可以加入网站底部技术群,一起找bug,另外新版作图神器,ChatGPT4 已上线 https://cube.waixingyun.cn/home

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

这就是 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 添加到你的代码库中。

交流

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。


王大冶
68.2k 声望105k 粉丝