请求的封装,先在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里面使用他

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

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

  

 

vue的搭建项目的更多相关文章

  1. 1.vue脚手架搭建项目

    前言: 在使用Vue-cli脚手架搭建项目之前,需要安装node.js和npm以及vue-cli. 开始搭建项目: 1.打开cmd win+R 2.转到要搭建的项目路径: g: cd Webapp/v ...

  2. Vue环境搭建-项目的创建-启动生命周期-组件的封装及应用

    vue项目环境的搭建 """ node >>> python:node是用c++编写用来运行js代码的 npm(cnpm) >>> p ...

  3. Vue脚手架搭建项目

    全局安装vue脚手架 $ npm install -g vue-cli 卸载方法 $ npm uninstall -g vue-cli 查看vue版本(注意:大写的V) $ vue -V 创建项目 $ ...

  4. 使用vue脚手架搭建项目并将px自动转化为rem

    一.安装node.js环境 二.node.js安装完成后使用npm安装vue脚手架vue-cli和安装webpack,我这里用cnpm cnpm i @vue/cli -g //全局安装脚手架3.0 ...

  5. vue cli搭建项目及文件引入

    cli搭建方法:需安装nodejs先 1.npm install -g cnpm --registry=https://registry.npm.taobao.org //安装cnpm,用cnpm下载 ...

  6. nodejs使用vue从搭建项目到发布部署

    都说是使用vue 脚手架自然用的是vue-cli npm install vue-cli -g 建立项目 vue init webpack demo //vue初始化 使用webpack 项目名称 这 ...

  7. 【vue】vue +element 搭建项目,mock模拟数据(纯干货)

    1.安装mockjs依赖 (c)npm install mockjs --save-dev 2.安装axios(Ajax) (c)npm install --save axios 3.项目目录 4.设 ...

  8. 使用VUE框架搭建项目基本步骤

    ps:初入Vue坑的小伙伴们,对于独立做一个项目可能不清楚需要使用哪些资源,这篇随笔希望对大家有所帮助. 第一步:参照vue的官方文档,建立一个vue的项目 # 全局安装 vue-cli $ npm ...

  9. vue+webpack搭建项目

    1.全局安装node.js 2.安装vue-cli 可以在项目目录安装 npm install -g vue-cli 使用vue-list命令选择webpack模板 vue init webpack ...

  10. VUE神速搭建项目

    1.npm install -g vue-cli 全局安装vue-cli脚手架 2.vue init webpack vueTest 初始化一个基于webpack的项目 3.cd vueTest 进入 ...

随机推荐

  1. springboot集成schedule

    背景 在项目开发过程中,我们经常需要执行具有周期性的任务.通过定时任务可以很好的帮助我们实现. 我们拿常用的几种定时任务框架做一个比较: 从以上表格可以看出,Spring Schedule框架功能完善 ...

  2. Nginx 流量和连接数限制

    1.Nginx流量限制 实现流量限制由两个指令 limit_rate 和 limit_rate_after 共同完成: limit_rate 语法:limit_rate rate; 默认值:limit ...

  3. Java邮件发送

    Java中发送邮件的方法之一,需要用到spring框架集成的JavaMailSenderImpl.SimpleMailMessage两个实现类. 一,创建一个service,代码如下: public ...

  4. 通过jedis远程访问redis服务器

    一.jedis简介 类似于mysql数据库,一般开发都需要通过代码去访问redis服务器,对于主流的开发语言,redis提供了访问的客户端接口. https://redis.io/clients 而对 ...

  5. c#+CAD动态移动效果

    public class MoveRotateScaleJig : DrawJig { public static List<Entity> entities = new List< ...

  6. angular4中引入quill editor

    1. npm install --save-dev @types/quill  安装types 2.npm install ng2-quill-editor --save 安装quill 3.配置ts ...

  7. keepalive配置mysql自动故障转移

    keepalive配置mysql自动故障转移 原创 2016年02月29日 02:16:52 2640 本文先配置了一个双master环境,互为主从,然后通过Keepalive配置了一个虚拟IP,客户 ...

  8. JAVA相关技术

    开发服务器环境: 1.Linux系统 CentOS 6.5\7 2.JDK1.8 3.tomcat 9 4.mysql 5.7 开发环境: 1.开发集成工具:idea 2.构建工具maven 仓库暂时 ...

  9. pinyin.js

    export default { a: "\u554a\u963f\u9515", ai: "\u57c3\u6328\u54ce\u5509\u54c0\u7691\u ...

  10. tensorflow/threading 用到的一些函数

    ---恢复内容开始--- import tensorflow as tf 1    tf.squeeze([1,2,3,4])  删除所有为1的维度   eg shape从(1,2,3,1)到(2,3 ...