vue的搭建项目

时间:2020-12-13 09:43:41

请求的封装,先在src下面创建一个utils的文件夹,文件夹里面有ajax.js loading.js index.js to

1 请求的封装 ajax文件 需要引入的文件在后面

/*
* [page ajax]
*/
import qs from 'qs'
import axios from 'axios'
import { host } from '../config'
import $load from './loading'
import $toast from './toast' const service = axios.create({
baseURL: host,
timeout: 6e4,
validateStatus: x => x === 200
}) /**
* 統一樣式的狀態碼處理
* @param {any} h 囘調
* @returns {null} 無
*/
const done = function(h){
return this.then(h).catch(({ code, msg }) => {
console.error('請求出錯啦 =>', code, msg)
})
} /**
* 請求發送前處理
* @param {any} o 配置前
* @returns {object} 配置後
*/
const onsend = o => {
// const token = $store.state.userInfo.Data.Token
// this.$vux.loading.show({
// text: '加载中'
// });
//$load.loadIn()
if (typeof o.data === 'string'){
o.headers[o.method]['Content-Type'] = 'application/json'
}
else if (Array.isArray(o.data)){
const form = new FormData() Object.entries(o.data[0]).forEach(([ k, v ]) => {
if (Array.isArray(v)){
v.forEach(x => form.append(k, x))
}
else {
form.append(k, v)
}
}) o.data = form
}
else {
o.data = qs.stringify(o.data)
} // if (token){
// // o.headers.common.Authorization = token
// }
return o
} /**
* 請求成功囘調
* @param {object} o 請求對象
* @returns {object} 響應
*/
const onsuccess = o => {
console.log('請求結果 =>', o.data)
$load.loadOut()
if (o.status !== 200){
throw o.status
} // 此處數據有後臺api數據格式決定
const { success, message, data } = o.data if (success === true){
return data
}
else if(success == false){
return $toast(message)
} throw {
success,
Message
}
} /**
* 請求失敗囘調
* @param {any} e 錯誤信息
* @returns {any} 無
*/
const onerror = e => {
$load.loadOut()
const info = e.toString()
const err = {
Code: -1,
Message: '请求失败'
} if (info.includes('Network Error')){
err.Message = '网络错误'
}
else if (info.includes('timeout of')){
err.Message = '请求超时'
} // console.log('error =>', e)
$toast(err.Message)
throw err
} Promise.prototype.done = done
window.Promise.prototype.done = done
service.interceptors.request.use(onsend)
service.interceptors.response.use(onsuccess, onerror) export default {
$get: (url, params) => service.get(url, { params }),
$pop: (url, params) => service.delete(url, { params }),
$put: (url, o) => service.put(url, o),
$post: (url, o) => service.post(url, o),
$patch: (url, o) => service.patch(url, o),
$form: (url, o) => service.post(url, [o]),
$auth: url => service.get(url, { responseType: 'blob' }).then(o => ({
key: o.headers.key,
data: o.data
}))
}

 index

// import filter from './filter'
import ajax from './ajax'
// import {elem} from './elem'
// import $bridge from './bridge.js'
import $toast from './toast.js'
import $load from './loading' const $pick = (o = {}, b) => {
if (!(o instanceof Object)){
throw 'The parameter only can be an object'
} return Object.entries(o).reduce((p, [ k, v ]) => {
if (b && typeof v === 'boolean' || v){
p[k] = v
} return p
}, {})
} export default {
/* 注册插件 */
install(Vue, { store, router }) {
/* 路由设置 */
router.beforeEach((to, from, next) => {
next()
})
router.afterEach(() => {
window.scrollTo(0, 0)
}) /* 添加过滤器 */
// Object.entries (filter).forEach(f => Vue.filter(...f))
/* 添加UI组件 */
// Object.entries(elem).forEach(r => Vue.component(...r)) /* 添加自定义属性/方法 */
Object.assign(Vue.prototype, {
...ajax,
// $bridge,
$pick,
$toast,
$load
})
}
}

 loading.js文件

 /* eslint-disable */
/*
* @Author: nooldey
* @Author-Email: <nooldey@gmail.com>
* @Date: 2018-03-18 16:50:34
* @Last Modified by: Matt
* @Last Modified time: 2018-07-12 11:11:44
* @Description: 加载中提示
*/ /**
* 打開加載動畫
* @param {string} [text='正在加载...'] 提示文字
* @returns {Null} 無
*/
const loadIn = (text = '') => {
if (window.spin){
return
} window.spin = document.createElement('div')
window.spin.className = 'ui-spin'
window.spin.innerHTML = `<div class="spin"><i></i><span>${ text }</span></div>`
document.body.appendChild(window.spin)
} /**
* 關閉加載動畫
* @returns {Null} 無
*/
const loadOut = () => {
if (!window.spin){
return
} window.spin.classList.add('fade-out')
setTimeout(() => {
try {
document.body.removeChild(window.spin)
}
catch(e){}
finally {
if (window.spin){
delete window.spin
}
}
}, 250)
} export default {
loadIn,
loadOut
}

  toast文件

/**
*
*
* @param {String} t 提示文字
* @param {Function} fn 回调函数
* @returns {null} 无
*/
const toast = (t, fn) => {
if (window.toast){
return
} const tip = document.createElement('div')
tip.className = 'ui-toast'
tip.innerHTML = `<p>${ t }</p>`
document.body.appendChild(tip)
setTimeout(() => tip.classList.add('active'), 0)
window.toast = tip setTimeout(() => {
// if (!window.toast){
// return
// } tip.classList.remove('active')
setTimeout(() => {
try {
document.body.removeChild(tip)
}
catch(e){}
finally {
window.toast = null
} fn && fn()
}, 300)
}, 1500)
} export default toast

  最后在main.js里面使用他

vue的搭建项目

前端获取Token,后台需要配置

Access-Control-Expose-Headers : 'Authorization'
response.setHeader("Cache-Control","no-store");