init 初始化

This commit is contained in:
yuping
2022-11-28 11:33:26 +08:00
parent 6424a4857b
commit 89c47f7a60
14 changed files with 636 additions and 30 deletions

75
src/api/request.js Normal file
View File

@@ -0,0 +1,75 @@
import router from "@/router";
import {ref, watch} from "vue";
import axios from 'axios';
export function useRequest(_url, params = {}) {
const data = ref({})
const loading = ref(false)
watch(params, () => {
fetchData()
})
function fetchData() {
loading.value = true
request(_url, params).then(r => {
data.value = r.data
loading.value = false
})
}
fetchData()
return {
data,
loading,
fetchData,
};
}
export async function request(_url, params) {
const s = _url.split(' ')
let url = s[0]
const method = s[1] || '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) {
if (response.code === 3 || response.code === 4 || response.code === 100) {
// router.push({path: '/login'})
return
} else {
// response.showMsg && notification.open({
// message: response.showMsg,
// duration: 2,
// });
return
}
}
return response
}).catch(e => {
console.log(2222)
console.log(e)
// router.push({path: '/login'})
})
}