mirror of
https://codeup.aliyun.com/67762337eccfc218f6110e0e/vue/student-h5.git
synced 2025-12-09 02:46:47 +08:00
init 初始化
This commit is contained in:
75
src/api/request.js
Normal file
75
src/api/request.js
Normal 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'})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user