Files
fe-student/src/api/request.js
2022-12-12 12:29:04 +08:00

112 lines
2.9 KiB
JavaScript

import router from "@/router";
import {reactive, ref, toRefs, watch} from "vue";
import axios from 'axios';
export function usePage(_url, param) {
const state = reactive({
data: {},
loading: false,
total: 0,
size: 10,
current: 1,
params: {pageNo: 1, pageSize: 10, ...param}
})
watch(param, () => {
state.params = {...state.params, ...param}
fetchData()
})
function fetchData() {
state.loading = true
request(_url, state.params).then(r => {
state.params.pageNo === 1 ? (state.data = r.data.records) : (state.data = [...state.data, ...r.data.records])
state.size = r.data.size
state.total = r.data.total
state.current = r.data.current
state.loading = false
})
}
fetchData()
return {
...toRefs(state),
fetchData,
};
}
export function useRequest(_url, params = {}) {
const state = reactive({
data: {},
loading: false,
})
watch(params, () => {
fetchData()
})
function fetchData() {
state.loading = true
request(_url, params).then(r => {
state.data = r.data
state.loading = false
})
}
fetchData()
return {
...toRefs(state),
fetchData,
};
}
export async function request(_url, params) {
const s = _url.split(' ')
let url = s[0]
const method = s[1]?.toLowerCase() || 'get'
if (method === 'get') {
let paramsArray = [];
//拼接参数
if (params) {
Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
}
const body = method !== 'get' ? params || {} : {}
return axios({
url,
method,
headers: {
'X-Token': localStorage.getItem('token'),
...method !== 'get' ? {'Content-Type': 'application/json'} : {}
},
baseURL: '',
...method !== 'get' ? {data: JSON.stringify(body)} : {}
}).then(resp => resp.data).then(response => {
if (response.code !== 200 && response.code !== 0) {
console.log(1111111111)
console.log(response.code)
if (import.meta.env.DEV && response.code === 1000) {
router.push({path: '/login'})
} else {
// response.showMsg && notification.open({
// message: response.showMsg,
// duration: 2,
// });
}
throw new Error('接口异常')
}
return response
}).catch(e => {
console.log(2222)
console.log(e)
// router.push({path: '/login'})
})
}