vue3 在axios下边封装了一个共用的方法 在页面怎么使用 最便捷
时间: 2024-03-08 22:49:29 浏览: 8
首先,在Vue3中,你可以在一个单独的文件中封装你的axios请求方法,例如 `api.js` 文件。然后,你可以在需要使用这些方法的组件中导入这些方法并使用它们。
下面是一个示例:
在 `api.js` 中,你可以编写以下的代码:
```javascript
import axios from 'axios';
export const fetchData = async (url) => {
const response = await axios.get(url);
return response.data;
};
export const postData = async (url, data) => {
const response = await axios.post(url, data);
return response.data;
};
// 添加其他需要的方法...
```
然后,在你的组件中,你可以导入你的 `api.js` 文件,并使用其中的方法:
```javascript
import { fetchData, postData } from './api.js';
export default {
data() {
return {
posts: [],
errorMessage: '',
};
},
created() {
this.fetchPosts();
},
methods: {
async fetchPosts() {
try {
const data = await fetchData('/api/posts');
this.posts = data;
} catch (error) {
this.errorMessage = 'Unable to fetch posts.';
}
},
async createPost(post) {
try {
const data = await postData('/api/posts', post);
this.posts.push(data);
} catch (error) {
this.errorMessage = 'Unable to create post.';
}
},
// 添加其他需要的方法...
},
};
```
这样,你就可以在你的组件中轻松使用这些封装的方法来请求数据。