MST

星途 面试题库

面试题:Vue中使用Vue Composition API如何处理基本的异步数据获取逻辑

在Vue Composition API中,假设你需要从一个API接口获取用户列表数据,简述实现步骤并给出关键代码示例,包括如何处理loading状态和错误处理。
11.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 安装并引入axios(假设使用axios进行HTTP请求)
    • 首先确保项目中安装了axios,如果没有安装,可以使用npm install axiosyarn add axios进行安装。
    • 在需要的地方引入axios,例如在main.js中全局引入:
import axios from 'axios'
Vue.prototype.$axios = axios
  1. 在Vue组件中使用Composition API获取数据
    • 导入refonMounted等Composition API相关函数。
    • 使用ref定义数据、loading状态和错误信息。
    • onMounted钩子函数中发送HTTP请求获取用户列表数据,并处理loading状态和错误。
<template>
  <div>
    <div v-if="loading">Loading...</div>
    <div v-if="error">{{ error }}</div>
    <ul v-else>
      <li v-for="user in users" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const users = ref([])
const loading = ref(false)
const error = ref('')

onMounted(async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/users')
    users.value = response.data
  } catch (e) {
    error.value = 'Error fetching user list'
  } finally {
    loading.value = false
  }
})
</script>

上述代码实现了在Vue组件中使用Composition API获取用户列表数据,并处理了加载状态和错误情况。在模板中根据loadingerror的值显示相应的提示信息,获取到的数据则展示在无序列表中。