// Axios 和 Vue 结合使用的示例代码
// 首先确保你已经在项目中安装了 axios 和 vue
// 可以使用 npm 或 yarn 安装:
// npm install axios vue
// 或者
// yarn add axios vue
// 引入 Vue 和 axios
import Vue from 'vue';
import axios from 'axios';
// 创建一个 Vue 实例
new Vue({
el: '#app',
data: {
message: 'Hello, World!',
posts: [] // 用于存储从 API 获取的数据
},
created() {
// 在组件创建时调用 fetchPosts 方法
this.fetchPosts();
},
methods: {
// 使用 axios 发送 GET 请求获取数据
fetchPosts() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
// 请求成功后将响应数据赋值给 posts
this.posts = response.data;
})
.catch(error => {
// 请求失败时处理错误
console.error('There was an error fetching the posts!', error);
});
}
}
});
/*
解释说明:
1. 通过 `import` 语句引入 Vue 和 axios。
2. 创建一个新的 Vue 实例,并在 `data` 中定义了一个空数组 `posts` 来存储从 API 获取的数据。
3. 在 `created` 生命周期钩子中调用 `fetchPosts` 方法,该方法会发送一个 GET 请求到指定的 API 地址。
4. 如果请求成功,`response.data` 将被赋值给 `posts`,并在页面上显示;如果请求失败,则会在控制台输出错误信息。
*/
上一篇:vue获取div高度
下一篇:vue3使用ref
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站