首页 > 其他分享 >026、Vue3+TypeScript基础,使用async和await来异步读取axios的网络图片

026、Vue3+TypeScript基础,使用async和await来异步读取axios的网络图片

时间:2024-08-18 16:38:59浏览次数:11  
标签:axios num vue import Vue3 TypeScript 026 10px async

01、App.vue代码如下:

<template>
  <div class="app">
    <h2>App.Vue</h2>
    <Person/>
  </div>
</template>

<script lang="ts" setup name="App">
// JS或TS
import Person from './view/Person.vue';
</script>

<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>

02、Person.vue代码如下:

<template>
  <div class="person">
    <h2>当前数值为:{{ num }}</h2>
    <button @click="add">点我+1</button><hr>
    <img v-for="(dog,index) in dogList" :src="dog" :key="index"><br>
    <button @click="getDog">获取小狗</button>
  </div>
</template>

<script lang="ts" name="Person001" setup>
import {reactive, ref} from 'vue'
import axios from 'axios'

// 数值增加
const num = ref(0)
function add() {
  num.value++
}

// 抓取图片
let dogList = reactive([
  'https://images.dog.ceo/breeds/pembroke/n02113023_4373.jpg'
])
// 异步函数
async function getDog() {
  try {
    let result = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
    dogList.push(result.data.message)
  } catch (error) {
    console.log(error)
  }
}

</script>
<style scoped>
.person {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;

  button {
    margin: 0 5px;
  }

  img {
    max-width: 100px;
    height: 100px;
    margin: 10px;
  }
}
</style>

03、效果如下:

 04、浏览器效果如下:

 

标签:axios,num,vue,import,Vue3,TypeScript,026,10px,async
From: https://www.cnblogs.com/tianpan2019/p/18365765

相关文章