Vue 3教程 - HTTP请求


fetch

mounted() {
  fetch('YOUR_URL')
    .then((resp) => reps.json())
    .then(data => {
      console.log(data);
      this.xxx = data;
    })
    .catch(err => console.log(err.message));
}

使用axios

安装axios

yarn add axios

使用JSON placeholder

网址:https://jsonplaceholder.typicode.com/

GET请求

<template>
  <button @click="loadStudents">Load Students</button>
  <div v-for="student in students" :key="student.id">
      <h3>{{ student.name }}</h3>
      <div>{{ student.intro }}</div>
  </div>  
</template>

<script>
import axios from 'axios';

export default {
  name: 'StudentList',
  data() {
    return {
      students: [],
    }
  },
  methods: {
    loadStudents() {
      axios.get(URL)
        .then(response => {
          this.studetns = response.data;
        })
        .catch(err => {
          console.log(err);
        })
    }
  }
}
</script>  

一般情况下,经常会把装载函数放在created()生命周期函数中:

created() {
  this.loadStudents();
}

POST请求

createPost() {
  axios.post(URL, this.formData)
    .then(response => {
      console.log(response);
    })
    .catch(err => {
      console.log(err);
    })
}

文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !
  目录