代码:
<template>
<div class="nihao">
<button @click="getDog">获取狗的图片</button>
<br>
<img :src="i" />
</div>
</template>
<script setup>
import axios from 'axios'
import { ref } from 'vue';
let i = ref()
function getDog(){
// 然后就可以使用axios发起HTTP请求了,比如:
axios.get('https://dog.ceo/api/breed/pembroke/images/random')
.then(response => {
console.log(response.data)
i.value = response.data.message
})
.catch(error => {
console.error(error);
});
}
</script>
<style scoped>
.nihao{
background-color: bisque;
height: auto;
}
</style>
说明:
- 先安装axios,命令:npm install axios
- 导入axios:import axios from 'axios'
- 使用:在函数中 axios.get().then().catch()
- 案例中请求地址为一个公共api,注意使用安全
- dom中img设置src属性,这里src是绑定状态,使用“:”
- 使用ref进行双向数据绑定,函数中给变量赋值的时候需要使用value