首页 > 其他分享 >vue3中的hook自定义函数

vue3中的hook自定义函数

时间:2022-09-26 15:55:15浏览次数:63  
标签:loading 自定义 errorMsg value hook vue3 useAxios data

1. 建立hook文件夹,在hook文件夹里面建立 useAxios.ts 文件,内容如下:

import { ref } from 'vue';
import axios from 'axios';

export default function<T>(url: string, method: string, param?: object) {
  const loading = ref(true);
  const data = ref<T | null>(null);
  const errorMsg = ref('');

  if (method === 'get') {
    axios.get(url).then(res => {
      loading.value = false;
      data.value = res.data;
    }).catch(err => {
      loading.value = false;
      errorMsg.value = err.message || '未知错误';
    })
  }

  if (method === 'post') {
    axios.post(url, param).then(res => {
      loading.value = false;
      data.value = res.data;
    }).catch(err => {
      loading.value = false;
      errorMsg.value = err.message || '未知错误';
    })
  }

  return {
    loading,
    data,
    errorMsg
  }
}

2. 在组件中使用

<script lang='ts'>
import { defineComponent } from 'vue'
import useAxios from './useAxios'

interface dataProps {
  n?: number,
  total?: number,
  money?: number
}

export default defineComponent ({
  setup() {
    const {loading, data, errorMsg} = useAxios<dataProps[]>('/myUrl/id=1','get')

    return {
      loading, 
      data, 
      errorMsg
    }
  },
})
</script>

 

 

标签:loading,自定义,errorMsg,value,hook,vue3,useAxios,data
From: https://www.cnblogs.com/suihung/p/16731209.html

相关文章