VUE怎么将发送请求与vue文件分开有什么好的封装方法吗
可以使用axios进行封装。
-
在src目录下新建一个api文件夹,用于存放所有的接口请求。
-
在api文件夹下新建一个index.js文件,用于统一管理所有的接口请求。
-
在index.js文件中使用axios进行封装,如下所示:
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:8080' // 设置请求的基础URL
export const getUserInfo = () => axios.get('/api/user') // 获取用户信息
export const login = data => axios.post('/api/login', data) // 用户登录
export const logout = () => axios.post('/api/logout') // 用户登出
- 在需要使用接口请求的组件中,引入api/index.js文件,并调用相应的接口函数即可。
import { getUserInfo } from '@/api'
export default {
created () {
getUserInfo().then(res => {
console.log(res.data)
}).catch(err => {
console.log(err)
})
}
}
这样就可以将发送请求与.vue文件分开,方便管理和维护。
原文地址: https://www.cveoy.top/t/topic/btJg 著作权归作者所有。请勿转载和采集!