vue3组合式函数

vue3的组合式函数的作用是封装和复用响应式状态的函数。只能在setup 标签的script标签汇总或者setup函数中使用。

普通的函数只能调用一次,但是组合式函数接受到响应式参数,当该值发生变化时,也会触发相关函数的重新加载。

如下
定义了一个,获取用户详情的组合式函数,封装到单独的js中,

import { ref, toValue, watchEffect } from 'vue'

 export function getUserInfo(url) {
    const data = ref(null)
    const error = ref(null)


    watchEffect(async () => {
        data.value = null
        error.value = null
        try {
            const res = await fetch(toValue(url))
            data.value = await res.json()
        } catch (e) { 
            error.value = e
        }
    })
    return {data,error}
}

在这里插入图片描述

函数返回2个响应式参数,data和error。
然后再Demo组件中引入该脚本,并将data和error渲染到页面上,
当url发生变化时,函数又重新被调用了。

<script setup lang="ts">
    import { ref ,computed} from 'vue'
import {getUserInfo} from '../pulic/fetch.user.js'
    
    //const url=ref("http://localhost:3000/user/info/query?id=1")

    const baseUrl = 'http://localhost:3000/user/info/query?id='
    const id = ref(1)
    const url = computed(() => baseUrl + id.value)

    const {data,error} = getUserInfo(url)
</script>

<template>
  <div>
    Load post id:
  <button v-for="i in 5" @click="id = i" :key="i">{{ i }}</button>
    <h1>{{ data }}</h1>
    <h1>{{ error }}</h1>
  </div>

</template>

点击1按钮
在这里插入图片描述
点击2按钮
在这里插入图片描述

https://cn.vuejs.org/guide/reusability/composables.html

相关推荐

  1. Vue3 逻辑复用 - 组合函数

    2024-03-31 21:18:11       65 阅读
  2. vue3组合函数

    2024-03-31 21:18:11       47 阅读
  3. Vue3 组合 API: reactive 和 ref 函数

    2024-03-31 21:18:11       43 阅读
  4. Vue 3 组合API深度剖析:工具函数详解

    2024-03-31 21:18:11       40 阅读
  5. Vue函数组件

    2024-03-31 21:18:11       30 阅读
  6. Vue组合函数,详细解析

    2024-03-31 21:18:11       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 21:18:11       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 21:18:11       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 21:18:11       82 阅读
  4. Python语言-面向对象

    2024-03-31 21:18:11       91 阅读

热门阅读

  1. Dockerfile中DSL语法

    2024-03-31 21:18:11       35 阅读
  2. python之@overload

    2024-03-31 21:18:11       45 阅读
  3. Spring Boot(版本:3.2.4)入门

    2024-03-31 21:18:11       38 阅读
  4. 队列的基本概念

    2024-03-31 21:18:11       38 阅读
  5. Android TV 应用中的遥控器按键事件处理

    2024-03-31 21:18:11       42 阅读
  6. FastAPI+React全栈开发11 开始使用FastAPI

    2024-03-31 21:18:11       40 阅读
  7. 5.FPGA运算符详解

    2024-03-31 21:18:11       35 阅读
  8. C# 系统学习(事件与委托 )

    2024-03-31 21:18:11       37 阅读
  9. 【n个n相加求和,从1~n,金币】

    2024-03-31 21:18:11       32 阅读