收藏990
分享
阅读24189
更新时间2025-08-22
要从 Vue 中的服务器获取数据,我们可以使用 JavaScript fetch() 方法。
当我们在本教程中使用 fetch() 方法时,我们不会指定HTTP请求方法,这意味着后台使用默认的 GET 请求方法。
fetch() 方法需要一个 URL 地址作为参数,以便它知道从哪里获取数据。
这是一个简单的示例,它使用 fetch() 方法发送 HTTP GET 请求,并接收数据作为 HTTP 响应。 本例中请求的数据是本地文件 file.txt 中的文本:
App.vue:
<template>
<div>
<button @click="fetchData">Fetch Data</button>
<p v-if="data">{{ data }}</p>
</div>
</template>
<script>
export default {
data() {
return {
data: null,
};
},
methods: {
fetchData() {
const response = fetch("file.txt");
this.data = response;
}
}
};
</script>
运行示例 »
在上面的例子中,我们只得到"[object Promise]"作为结果,但这不是我们想要的。
我们得到这个结果是因为 fetch() 是一个基于 Promise 的方法,它返回一个 Promise 对象。 因此,fetch() 方法给出的第一个返回只是一个对象,这意味着 HTTP 请求已发送。 这是"pending"(待处理)状态。
当 fetch() 方法真正获取到我们想要的数据时,承诺就得到了履行。
要等待响应完成,并获取我们想要的数据,我们需要在 fetch() 方法前面使用 await 运算符:
const response = await fetch("file.txt");
当方法内部使用 await 运算符时,需要使用 async 运算符声明该方法:
async fetchData() {
const response = await fetch("file.txt");
this.data = response;
}
async 运算符告诉浏览器该方法是异步的,这意味着它正在等待某些事情,浏览器可以在等待该方法完成的同时继续执行其他任务。
现在我们得到的是一个"Response",而不再只是一个"Promise",这意味着我们离获取 file.txt 文件中的实际文本又近了一步:
App.vue:
<template>
<div>
<button @click="fetchData">Fetch Data</button>
<p v-if="data">{{ data }}</p>
</div>
</template>
<script>
export default {
data() {
return {
data: null,
};
},
methods: {
async fetchData() {
const response = await fetch("file.txt");
this.data = response;
}
}
};
</script>
运行示例 »
要获取 file.txt 文件中的文本,我们需要在响应上使用 text() 方法。 由于 text() 方法是基于 Promise 的方法,因此我们需要在其前面使用 await 运算符。
终于! 现在我们已经有了使用 fetch() 方法从 file.txt 文件中获取文本所需的内容:
App.vue:
<template>
<div>
<button @click="fetchData">Fetch Data</button>
<p v-if="data">{{ data }}</p>
</div>
</template>
<script>
export default {
data() {
return {
data: null,
};
},
methods: {
async fetchData() {
const response = await fetch("file.txt");
this.data = await response.text();
}
}
};
</script>
运行示例 »
在前面的示例中,我们从 .txt 文件中获取文本。 但是存储数据的方法有很多,现在我们将了解如何从 .json 文件中获取信息。
JSON 是一种易于使用的常见文件格式,因为数据以文本形式存储,因此易于人类阅读,并且 JSON 格式也受到编程语言的广泛支持,因此我们可以,例如 ,指定从 .json 文件中提取哪些数据。
要从 .json 文件读取数据,我们需要对上面的示例做的唯一更改是获取 .json 文件,并在响应中使用 json() 方法而不是 text() 方法。
json() 方法读取 HTTP 请求的响应并返回 JavaScript 对象。
我们在这里使用 <pre> 标签来显示 JSON 格式的文本,因为它保留空格和换行符,以便更容易阅读。
App.vue:
<template>
<div>
<button @click="fetchData">Fetch Data</button>
<pre v-if="data">{{ data }}</pre>
</div>
</template>
<script>
export default {
data() {
return {
data: null,
};
},
methods: {
async fetchData() {
const response = await fetch("bigLandMammals.json");
this.data = await response.json();
}
}
};
</script>
运行示例 »
由于 json() 方法的结果是一个 JavaScript 对象,因此我们可以修改上面的示例以显示 bigLandMammals.json 文件中的随机动物:
App.vue:
<template>
<p>尝试多次单击该按钮以查看随机挑选的新动物。</p>
<button @click="fetchData">Fetch Data</button>
<div v-if="randomMammal">
<h2>{{ randomMammal.name }}</h2>
<p>Max weight: {{ randomMammal.maxWeight }} kg</p>
</div>
</template>
<script>
export default {
data() {
return {
randomMammal: null
};
},
methods: {
async fetchData() {
const response = await fetch("bigLandMammals.json");
const data = await response.json();
const randIndex = Math.floor(Math.random()*data.results.length);
this.randomMammal = data.results[randIndex];
}
}
};
</script>
运行示例 »
API 代表 Application Programming Interface。 您可以此处了解有关API的更多信息。
我们可以连接和使用许多有趣的免费 API,以获取天气数据、证券交易所数据等。
当我们通过 HTTP 请求调用 API 时得到的响应可以包含各种数据,但通常包含 JSON 格式的数据。
单击按钮即可从 random-data-api.com API 获取随机用户。
App.vue:
<template>
<h1>示例</h1>
<p>单击该按钮可通过 HTTP 请求获取数据。</p>
<p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>
<p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>
<button @click="fetchData">Fetch data</button>
<pre v-if="data">{{ data }}</pre>
</template>
<script>
export default {
data() {
return {
data: null,
};
},
methods: {
async fetchData() {
const response = await fetch("https://random-data-api.com/api/v2/users");
this.data = await response.json();
}
}
};
</script>
运行示例 »
我们可以稍微修改一下之前的示例,以更加用户友好的方式包含随机用户:
单击按钮时,我们会在 <pre> 标签中显示随机用户名,以及职位名称和图像。
App.vue:
<template>
<h1>示例</h1>
<p>单击该按钮可通过 HTTP 请求获取数据。</p>
<p>每次点击都会生成一个带有 <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a> 中的随机用户的对象。</p>
<p>机器人头像由 <a href="http://Robohash.org" target="_blank">RoboHash</a> 精心送出。</p>
<button @click="fetchData">Fetch data</button>
<div v-if="data" id="dataDiv">
<img :src="data.avatar" alt="avatar">
<pre>{{ data.first_name + " " + data.last_name }}</pre>
<p>"{{ data.employment.title }}"</p>
</div>
</template>
<script>
export default {
data() {
return {
data: null,
};
},
methods: {
async fetchData() {
const response = await fetch("https://random-data-api.com/api/v2/users");
this.data = await response.json();
},
}
};
</script>
<style>
#dataDiv {
width: 240px;
background-color: aquamarine;
border: solid black 1px;
margin-top: 10px;
padding: 10px;
}
#dataDiv > img {
width: 100%;
}
pre {
font-size: larger;
font-weight: bold;
}
</style>
运行示例 »
"axios"JavaScript 库还允许我们发出 HTTP 请求。
要在您自己的计算机上创建并运行示例,您首先需要使用项目文件夹中的终端安装"axios"库,如下所示:
npm install axios这就是我们如何使用 Vue 中的"axios"库来获取随机用户:
仅对前面的示例进行一些小的更改,以使用"axios"库执行 HTTP 请求。
App.vue:
<template>
<h1>示例</h1>
<p>单击该按钮可通过 HTTP 请求获取数据。</p>
<p>每次点击都会生成一个带有 <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a> 中的随机用户的对象。</p>
<p>机器人头像由 <a href="http://Robohash.org" target="_blank">RoboHash</a> 精心送出。</p>
<button @click="fetchData">Fetch data</button>
<div v-if="data" id="dataDiv">
<img :src="data.data.avatar" alt="avatar">
<pre>{{ data.data.first_name + " " + data.data.last_name }}</pre>
<p>"{{ data.data.employment.title }}"</p>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
data: null,
};
},
methods: {
async fetchData() {
this.data = await axios.get("https://random-data-api.com/api/v2/users");
}
}
};
</script>
<style>
#dataDiv {
width: 240px;
background-color: aquamarine;
border: solid black 1px;
margin-top: 10px;
padding: 10px;
}
#dataDiv > img {
width: 100%;
}
pre {
font-size: larger;
font-weight: bold;
}
</style>
运行示例 »
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.3万人学习
共49课时
77.4万人学习
共29课时
62万人学习
共25课时
39.5万人学习
共43课时
71.2万人学习
共25课时
61.9万人学习
共22课时
23.1万人学习
共28课时
34.1万人学习
共89课时
125.7万人学习