vue3之组合式函数

抽取成一个组合式函数:

// fetch.js
//接收响应式状态
import { ref, watchEffect, toValue  } from 'vue'
//一个封装的异步请求
import { fetch } from '../XX'
export function useFetch(url) {
	  const data = ref(null)
	  const error = ref(null)
	  const fetchData = () => {
	  	  // 重置data,error 数据
	      data.value = null
	      error.value = null
	      //toValue() 是一个在 3.3 版本中新增的 API。它的设计目的是将 ref 或 getter 规范化为值
		  fetch(toValue(url))
		    .then((res) => res.json())
		    .then((json) => (data.value = json))
		    .catch((err) => (error.value = err))
	  }
	 
	 watchEffect(() => {
	 	//只要fetchData函数中的url变就自动触发watchEffect
	   fetchData()
	 })
  return { data, error }
}

在组件里只需要这样使用:

<script setup>
import { useFetch } from './fetch.js'

// 当 props.id 改变时重新 fetch
const { data, error } = useFetch(() => `/posts/${props.id}`)
</script>

相关推荐

  1. vue3组合函数

    2024-03-15 21:12:01       23 阅读
  2. Vue3 逻辑复用 - 组合函数

    2024-03-15 21:12:01       39 阅读
  3. Vue3 组合 API: reactive 和 ref 函数

    2024-03-15 21:12:01       21 阅读
  4. Vue 3 组合API深度剖析:工具函数详解

    2024-03-15 21:12:01       17 阅读
  5. Vue函数组件

    2024-03-15 21:12:01       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-15 21:12:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-15 21:12:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-15 21:12:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-15 21:12:01       20 阅读

热门阅读

  1. TCP并发模型

    2024-03-15 21:12:01       19 阅读
  2. QT UI设计

    2024-03-15 21:12:01       18 阅读
  3. 数据血缘实现原理

    2024-03-15 21:12:01       18 阅读
  4. 模板方法模式在交易策略开发中的应用

    2024-03-15 21:12:01       18 阅读
  5. Greetings

    Greetings

    2024-03-15 21:12:01      16 阅读
  6. 面试精选-前端

    2024-03-15 21:12:01       18 阅读