vue3 网络操作
先写一个hook
// 得到所有的列表
import {ref} from "vue"
import axios from "axios"
import { v8IntrinsicIdentifier } from '@babel/types';
function getAllList(){
const Loading = ref(true);
const Loaded = ref(false);
const result = ref(null);
const error = ref(null);
// 获取列表
axios.get("https://api.ixiaowai.cn/tgrj/index.php")
.then(value=>{
// console.log(value)
Loading.value = false;
Loaded.value = true;
result.value = value.data;
}).catch(err=>{
Loading.value = false;
Loaded.value = true;
result.value = err.message;
})
return {
Loading,Loaded,result,error
}
}
// 返回这个函数
export default getAllList;
然后在根组件中使用就行了,这样就能实现加载前后的状态管理
<template>
<div class="container">
<h2 v-if="Loading">loading....</h2>
<p v-if="Loaded && !error">
{{result}}
</p>
<p v-if="Loaded && error">
{{error}}
</p>
</div>
</template>
<script lang="ts">
import { defineComponent, computed ,ref, watch} from 'vue';
import 'bootstrap/dist/css/bootstrap.min.css'
import getAllList from "./hook/loadUtil"
import axios from 'axios'
// 就会提供些额外的方法
export default defineComponent({
name: 'App',
// setup 方 法还不能为空,真的很奇葩的事情
setup(){
const {Loading,Loaded,result,error}= getAllList();
return {
Loading,Loaded,result,error
}
}
});
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
在加载之前会显示加载中状态,加载成功会正确显示数据,若加载失败,会显示加载失败的信息!