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);
})
}