返回

玩转 Vue 3 组合 API,轻松搞定数据请求

前端

Vue 3 中的组合 API 是一个非常强大的特性,它允许我们创建可重用的逻辑块,然后在不同的组件中使用这些逻辑块。这使得我们的代码更加模块化和可维护。

我们先创建一个简单的 Vue 3 应用。在 src 目录下创建一个 main.js 文件,并添加以下代码:

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

在 src 目录下创建一个 App.vue 文件,并添加以下代码:

<template>
  <div id="app">
    <h1>{{ message }}</h1>
  </div>
</template>

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

export default {
  setup() {
    const message = ref('Hello Vue 3!')

    onMounted(() => {
      // 在这里发起数据请求
    })

    return {
      message
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

然后,我们在 onMounted 钩子函数中发起数据请求。

import { ref, onMounted } from 'vue'

export default {
  setup() {
    const message = ref('Hello Vue 3!')

    onMounted(() => {
      // 在这里发起数据请求

      fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(res => res.json())
        .then(data => {
          // 将数据存储到 message 中
          message.value = data.title
        })
        .catch(error => {
          // 处理错误
          console.error(error)
        })
    })

    return {
      message
    }
  }
}

现在,我们已经成功地使用 Vue 3 的组合 API 发起了数据请求。我们可以通过在浏览器中打开 http://localhost:3000 来查看结果。