Function introduction
Open the html directly, and a cat photo will be displayed. Click the photo, and a new cat photo will be updated.
Implementation method
- Send request with Axios
- Use Vue to bind the img tag src attribute
Complete code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Axios Demo1</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@3.5.8/dist/vue.global.prod.js"></script>
</head>
<body>
<div style="margin:0 auto; text-align: center;" id="app">
<img v-if="imgSrc" :src="imgSrc" @click="refresh" >{{imgSrc?'':'加载中'}}</img>
</div>
<script>
const { createApp, ref, onMounted } = Vue
const App = {
setup(){
// var imgSrc = ref('https://www.baidu.com/img/flexible/logo/pc/result@2.png')
const imgSrc = ref('')
onMounted(() => {
axios.get('https://api.thecatapi.com/v1/images/search')
.then((res)=> {
// handle success
console.log(res);
imgSrc.value = res.data[0].url
})
})
const refresh = () => {
console.log('refresh')
axios.get('https://api.thecatapi.com/v1/images/search')
.then((res)=> {
// handle success
console.log(res);
imgSrc.value = res.data[0].url
})
}
return {
imgSrc,
refresh
}
}
}
createApp(App).mount('#app');
// console.log(Vue)
</script>
</body>
</html>