以下是我的代码:
useURLLoader.ts
import axios from 'axios'
function useURLLoader(url: string){
const result = ref(null)
const loading = ref(true)
const loaded = ref(false)
const error = ref(null)
axios.get(url).then((rawData)=> {
loading.value = false
loaded.value = true
result.value = rawData.data
}).catch(e => {
error.value = e
loaded.value = false
})
return {
result,
loading,
loaded,
error
}
}
export default useURLLoader
```<template>
<div id="app">
<img src="./assets/logo.png" alt="" />
<h1>{{ count }}</h1>
<h1>{{ double }}</h1>
<ul>
<li v-for="number in numbers" :key="number">
<h1>{{ number }}</h1>
</li>
</ul>
<h1>{{ person.name }}</h1>
<h1>{{ greetings }}</h1>
<h1>x:{{ x }}</h1>
<h1>y:{{ y }}</h1>
<h1 v-if="loading">loading...</h1>
<img v-if="loaded" :src="result.message" alt="" />
<button @click="increase">?+1</button>
<button @click="updateGreetings">updateGreetings</button>
</div>
</template>
<script lang="ts">
import {
computed,
ref,
reactive,
toRefs,
onMounted,
onUpdated,
onRenderTriggered,
watch,
onUnmounted,
} from "vue";
import useMousePosition from "./hooks/useMousePosition";
import useURLLoader from "./hooks/useURLLoader";
export default {
mame: "App",
setup() {
const { result, loaded, loading } = useURLLoader(
"https://dog.ceo/api/breeds/image/random"
);
return {
result,
loaded,
loading,
};
},
};
</script>
<style>
#app {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>