vue3 hooks

358 阅读1分钟
import { ref, Ref } from 'vue'

export default function useApi(url, options) {    
    const response = ref()    
    const request = async () => {        
        const res = await fetch(url, options)        
        const data = await res.json()        
        response.value = data.data    
    }  

    return { response, request }
}

相较于Vue2,可以抽取复用项目中的一些公共的业务逻辑,可以根据文件区分,增加了项目的耦合性,便于维护

如何使用?

setup() {        
    const { response, request } = useApi('http://localhost:3002/getIndex')     
       onMounted(async function() {          
          await request()       
     })        
    return {            
        response       
     }  
  }