Commit 364c2fbd authored by 姬鋆屾's avatar 姬鋆屾

fixed:修复token过期无法回到登录页的问题

parent 33ed8a80
...@@ -8,15 +8,13 @@ export default { ...@@ -8,15 +8,13 @@ export default {
methods: { methods: {
// 渲染前置处理 // 渲染前置处理
beforeRender(data) { beforeRender(data) {
return data return data;
}, },
// 渲染后置处理 // 渲染后置处理
afterRender(data) { afterRender(data) {},
},
// 提交表单的前置处理 // 提交表单的前置处理
beforeSubmit(data) { beforeSubmit(data) {
return data return data;
}, },
// 提交表单的后置处理, 会阻断默认的回退行为 // 提交表单的后置处理, 会阻断默认的回退行为
afterSubmit(data) { afterSubmit(data) {
...@@ -38,16 +36,18 @@ export default { ...@@ -38,16 +36,18 @@ export default {
this.dict = Object.assign({}, this.dict, res.dict); this.dict = Object.assign({}, this.dict, res.dict);
this.afterRender(res); this.afterRender(res);
}) })
.catch(error => { .catch((error) => {
console.error(error)
this.$message.error(error.message); this.$message.error(error.message);
error.message.indexOf("过期") > -1
? (window.location = "/#/login")
: "";
}) })
.then(data => { .then((data) => {
clearTimeout(this.loadingTimer); clearTimeout(this.loadingTimer);
this.loadingTimer = setTimeout(() => { this.loadingTimer = setTimeout(() => {
this.loading = false; this.loading = false;
}, 300); }, 300);
}) });
}, },
// 提交表单 // 提交表单
submitForm(ref) { submitForm(ref) {
...@@ -55,72 +55,81 @@ export default { ...@@ -55,72 +55,81 @@ export default {
el.validate((valid) => { el.validate((valid) => {
if (!valid) return; if (!valid) return;
this.loading = true; this.loading = true;
this.$post(this.urls.saveUrl || this.pageInfo.saveUrl, this.$post(
this.urls.saveUrl || this.pageInfo.saveUrl,
this.beforeSubmit(this.form) this.beforeSubmit(this.form)
) )
.then(res => { .then((res) => {
this.$message.success(res.msg); this.$message.success(res.msg);
this.afterSubmit(res); this.afterSubmit(res);
}) })
.catch(error => { .catch((error) => {
this.$message.error(error.message); this.$message.error(error.message);
}) })
.then(data => { .then((data) => {
clearTimeout(this.loadingTimer); clearTimeout(this.loadingTimer);
this.loadingTimer = setTimeout(() => { this.loadingTimer = setTimeout(() => {
this.loading = false; this.loading = false;
}, 200); }, 200);
}) });
}); });
}, },
// 复制一个数组或对象 // 复制一个数组或对象
util_copy(data) { util_copy(data) {
return JSON.parse(JSON.stringify(data)) return JSON.parse(JSON.stringify(data));
}, },
// 工具方法,把数字转化为字符串 // 工具方法,把数字转化为字符串
util_toString(data, array) { util_toString(data, array) {
//原始数据 //原始数据
const dataCopy = Object.assign({}, data); const dataCopy = Object.assign({}, data);
array.forEach(item => { array.forEach((item) => {
//如果相等做操作 //如果相等做操作
dataCopy[item] = dataCopy[item] === undefined ? '' : dataCopy[item] + ''; dataCopy[item] =
}) dataCopy[item] === undefined ? "" : dataCopy[item] + "";
});
return dataCopy; return dataCopy;
}, },
// 工具方法,把字符串转化为数组 // 工具方法,把字符串转化为数组
util_toArrays(data, array) { util_toArrays(data, array) {
const dataCopy = Object.assign({}, data); const dataCopy = Object.assign({}, data);
array.forEach(item => { array.forEach((item) => {
dataCopy[item] = dataCopy[item] === undefined ? [] : dataCopy[item].split(","); dataCopy[item] =
}) dataCopy[item] === undefined ? [] : dataCopy[item].split(",");
});
return dataCopy; return dataCopy;
}, },
// 工具方法,把字符串转化为格式化日期 // 工具方法,把字符串转化为格式化日期
util_toDateStr(data, array) { util_toDateStr(data, array) {
const dataCopy = Object.assign({}, data); const dataCopy = Object.assign({}, data);
array.forEach(item => { array.forEach((item) => {
dataCopy[item] = dataCopy[item] === undefined ? '' : this.util_formatterDate(dataCopy[item]); dataCopy[item] =
}) dataCopy[item] === undefined
? ""
: this.util_formatterDate(dataCopy[item]);
});
return dataCopy; return dataCopy;
}, },
util_formatterDate(time) { util_formatterDate(time) {
let date = new Date(Number(time)); let date = new Date(Number(time));
let Y = date.getFullYear() + '-'; let Y = date.getFullYear() + "-";
let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; let M =
let D = this.panLeft(date.getDate()) + ' '; (date.getMonth() + 1 < 10
let h = this.panLeft(date.getHours()) + ':'; ? "0" + (date.getMonth() + 1)
let m = this.panLeft(date.getMinutes()) + ':'; : date.getMonth() + 1) + "-";
let D = this.panLeft(date.getDate()) + " ";
let h = this.panLeft(date.getHours()) + ":";
let m = this.panLeft(date.getMinutes()) + ":";
let s = this.panLeft(date.getSeconds()); let s = this.panLeft(date.getSeconds());
return Y+M+D+h+m+s; return Y + M + D + h + m + s;
}, },
panLeft(num){ panLeft(num) {
return num < 10 ? '0'+num : num; return num < 10 ? "0" + num : num;
}, },
// 从dict字段暴力取值,取不到则返回原值 // 从dict字段暴力取值,取不到则返回原值
util_formatter(key, val) { util_formatter(key, val) {
try { try {
return this.dict[key][val] return this.dict[key][val];
} catch (error) { } catch (error) {
return val; return val;
} }
...@@ -133,24 +142,24 @@ export default { ...@@ -133,24 +142,24 @@ export default {
} }
}); });
}, 0); }, 0);
} },
}, },
computed: { computed: {
pageInfo() { pageInfo() {
let currUrl = this.$route.path; let currUrl = this.$route.path;
let urlArray = currUrl.split('/'); let urlArray = currUrl.split("/");
let type = urlArray.pop(); let type = urlArray.pop();
urlArray.push('save'); urlArray.push("save");
let saveUrl = urlArray.join('/'); let saveUrl = urlArray.join("/");
urlArray.pop(); urlArray.pop();
urlArray.push('edit'); urlArray.push("edit");
let editUrl = urlArray.join('/'); let editUrl = urlArray.join("/");
urlArray.pop(); urlArray.pop();
urlArray.push('add'); urlArray.push("add");
let addUrl = urlArray.join('/'); let addUrl = urlArray.join("/");
urlArray.pop(); urlArray.pop();
urlArray.push('view'); urlArray.push("view");
let viewUrl = urlArray.join('/'); let viewUrl = urlArray.join("/");
return { return {
type, type,
currUrl, currUrl,
...@@ -174,9 +183,6 @@ export default { ...@@ -174,9 +183,6 @@ export default {
toString: [], // 需要把number转化为string的表单字段name数组 toString: [], // 需要把number转化为string的表单字段name数组
toArrays: [], // 需要把number转化为arrays的表单字段name数组 toArrays: [], // 需要把number转化为arrays的表单字段name数组
toDate: [], // 需要把number转化为date的表单字段name数组 toDate: [], // 需要把number转化为date的表单字段name数组
} };
} },
} };
...@@ -51,6 +51,9 @@ export default { ...@@ -51,6 +51,9 @@ export default {
}) })
.catch((error) => { .catch((error) => {
this.$message.error(error.message); this.$message.error(error.message);
error.message.indexOf("过期") > -1
? (window.location = "/#/login")
: "";
throw error; throw error;
}) })
.then((data) => { .then((data) => {
......
...@@ -64,7 +64,6 @@ export default { ...@@ -64,7 +64,6 @@ export default {
return; return;
} }
this.tableData.loading = true; this.tableData.loading = true;
console.log(this.query);
if (this.$route.path == "/user/list") { if (this.$route.path == "/user/list") {
this.query.userType this.query.userType
? (this.query.userTypeList = []) ? (this.query.userTypeList = [])
...@@ -82,8 +81,12 @@ export default { ...@@ -82,8 +81,12 @@ export default {
this.afterRender(this.tableData); this.afterRender(this.tableData);
}) })
.catch((error) => { .catch((error) => {
console.log(error);
if (error.message == "自动取消ajax操作") return; if (error.message == "自动取消ajax操作") return;
this.$message.error(error.message); this.$message.error(error.message);
error.message.indexOf("过期") > -1
? (window.location = "/#/login")
: "";
}) })
.then((data) => { .then((data) => {
clearTimeout(this.loadingTimer); clearTimeout(this.loadingTimer);
......
import axios from 'axios'; import axios from "axios";
import Qs from 'qs'; import Qs from "qs";
const JSONbig = require('json-bigint')({"storeAsString": true}); const JSONbig = require("json-bigint")({ storeAsString: true });
import cookie from './cookie'; import cookie from "./cookie";
import httpErrorHandler from './httpErrorHandler'; import httpErrorHandler from "./httpErrorHandler";
const instance = axios.create({ const instance = axios.create({
baseURL: '/enterprise', baseURL: "/enterprise",
headers: { headers: {
post: { post: {
'Content-Type': 'application/json;charset=UTF-8', "Content-Type": "application/json;charset=UTF-8",
'dataType': 'json', dataType: "json",
} },
}, },
transformResponse: [data=>{ transformResponse: [
(data) => {
try { try {
JSON.parse(data); JSON.parse(data);
return JSONbig.parse(data); return JSONbig.parse(data);
} catch (error) { } catch (error) {
return data; return data;
} }
}], },
],
}); });
instance.interceptors.request.use(
instance.interceptors.request.use(config => { (config) => {
//config.data = Qs.stringify(config.data, {arrayFormat: 'repeat', allowDots: true}); //config.data = Qs.stringify(config.data, {arrayFormat: 'repeat', allowDots: true});
//config.data = Qs.stringify(config.data, {arrayFormat: 'indices', allowDots: true}); //config.data = Qs.stringify(config.data, {arrayFormat: 'indices', allowDots: true});
//brackets //brackets
...@@ -31,16 +33,19 @@ instance.interceptors.request.use(config => { ...@@ -31,16 +33,19 @@ instance.interceptors.request.use(config => {
// config.headers['Content-Type'] = 'application/json;charset=UTF-8' // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
// config.headers.timestamp = Math.floor(new Date().getTime() / 1000) // config.headers.timestamp = Math.floor(new Date().getTime() / 1000)
// console.log("sessionStorage",window.sessionStorage) // console.log("sessionStorage",window.sessionStorage)
config.headers.Authorization = window.sessionStorage.getItem('token') || '' config.headers.Authorization = window.sessionStorage.getItem("token") || "";
//console.log("request config and session",config,window.sessionStorage); //console.log("request config and session",config,window.sessionStorage);
return config; return config;
}, err => { },
(err) => {
return Promise.reject(err); return Promise.reject(err);
}); }
);
instance.interceptors.response.use(response=>{ instance.interceptors.response.use((response) => {
return response.data return response.data;
},httpErrorHandler); }, httpErrorHandler);
/** /**
* 封装后的axios post方法 * 封装后的axios post方法
...@@ -53,8 +58,8 @@ instance.interceptors.response.use(response=>{ ...@@ -53,8 +58,8 @@ instance.interceptors.response.use(response=>{
export function post(url, option, config = {}) { export function post(url, option, config = {}) {
const data = Object.assign({}, option, { const data = Object.assign({}, option, {
// __mortals_token__: cookie.getItem('__mortals_token__'), // __mortals_token__: cookie.getItem('__mortals_token__'),
}) });
return instance.post(url, data, config) return instance.post(url, data, config, httpErrorHandler);
} }
/** /**
...@@ -68,24 +73,23 @@ export function post(url, option, config = {}) { ...@@ -68,24 +73,23 @@ export function post(url, option, config = {}) {
export function get(url, option, config = {}) { export function get(url, option, config = {}) {
const data = Object.assign({}, option, { const data = Object.assign({}, option, {
//__mortals_token__: cookie.getItem('__mortals_token__'), //__mortals_token__: cookie.getItem('__mortals_token__'),
}) });
return instance.get(url, { params: data }, config) return instance.get(url, { params: data }, config, httpErrorHandler);
} }
// 文件上传 // 文件上传
const uploadInstance = axios.create({ const uploadInstance = axios.create({
baseURL: '/m', baseURL: "/m",
headers: { headers: {
post: { post: {
'Content-Type': 'multipart/form-data', "Content-Type": "multipart/form-data",
} },
} },
}); });
uploadInstance.interceptors.response.use(response=>{ uploadInstance.interceptors.response.use((response) => {
return response.data return response.data;
},httpErrorHandler); }, httpErrorHandler);
/** /**
* 封装后的axios upload方法 * 封装后的axios upload方法
...@@ -97,8 +101,8 @@ uploadInstance.interceptors.response.use(response=>{ ...@@ -97,8 +101,8 @@ uploadInstance.interceptors.response.use(response=>{
*/ */
export function upload(url, option, config = {}) { export function upload(url, option, config = {}) {
let formdata = new FormData(); let formdata = new FormData();
Object.keys(option).forEach(key=>{ Object.keys(option).forEach((key) => {
formdata.append(key, option[key]) formdata.append(key, option[key]);
}) });
return uploadInstance.post(url, formdata, config) return uploadInstance.post(url, formdata, config);
} }
export default (error) => { export default (error) => {
if(error.message === '自动取消ajax操作') return Promise.reject(error); if (error.message === "自动取消ajax操作") return Promise.reject(error);
if (!error.response) { if (!error.response) {
console.error(error); console.error(error);
return Promise.reject({ return Promise.reject({
message: '未知错误', message: "未知错误",
error, error,
}); });
}; }
let tip = ''; let tip = "";
const status = error.response.status; const status = error.response.status;
switch (status) { switch (status) {
case 400: case 400:
tip = '错误的请求参数'; tip = "错误的请求参数";
break; break;
case 401: case 401:
tip = '没有该操作权限'; tip = "没有该操作权限";
break; break;
case 403: case 403:
tip = '用户未登录或登录失效,请重新登录'; tip = "用户未登录或登录失效,请重新登录";
break; break;
case 404: case 404:
tip = '错误的请求地址'; tip = "错误的请求地址";
break; break;
case 405: case 405:
tip = '请修改当前密码(原因:首次登录或超过期限未修改密码)'; tip = "请修改当前密码(原因:首次登录或超过期限未修改密码)";
break; break;
case 500: case 500:
case 501: case 501:
case 502: case 502:
case 503: case 503:
case 504: case 504:
tip = '服务器错误'; tip = "服务器错误";
break; break;
default: default:
tip = '未知错误' + status; tip = "未知错误" + status;
} }
if(status === 405){ if (status === 405) {
window.location='/#/login/updatePwd'; window.location = "/#/login/updatePwd";
}else{ } else {
tip +=',将自动返回主页'; tip += ",将自动返回主页";
window.location='/#/'; window.location = "/#/";
} }
return Promise.reject({ return Promise.reject({
...@@ -49,5 +50,4 @@ export default (error) => { ...@@ -49,5 +50,4 @@ export default (error) => {
error, error,
status, status,
}); });
} };
\ No newline at end of file
import Qs from 'qs'; import Qs from "qs";
import { post, get, upload } from './ajax'; import { post, get, upload } from "./ajax";
import queue from './queue'; import queue from "./queue";
import axios from 'axios'; import axios from "axios";
import cookie from './cookie'; import cookie from "./cookie";
import httpErrorHandler from './httpErrorHandler'; import httpErrorHandler from "./httpErrorHandler";
/** /**
* 获取参数的类型 * 获取参数的类型
...@@ -12,7 +12,7 @@ import httpErrorHandler from './httpErrorHandler'; ...@@ -12,7 +12,7 @@ import httpErrorHandler from './httpErrorHandler';
* @returns {string} 参数类型 * @returns {string} 参数类型
*/ */
export const type = (data) => { export const type = (data) => {
return Object.prototype.toString.call(data).replace(/(\[object |\])/g, '') return Object.prototype.toString.call(data).replace(/(\[object |\])/g, "");
}; };
/** /**
...@@ -22,7 +22,7 @@ export const type = (data) => { ...@@ -22,7 +22,7 @@ export const type = (data) => {
*/ */
export const getLoginStatus = () => { export const getLoginStatus = () => {
return window.sessionStorage.isLogin; return window.sessionStorage.isLogin;
} };
/** /**
* 解析url参数 * 解析url参数
...@@ -30,9 +30,8 @@ export const getLoginStatus = () => { ...@@ -30,9 +30,8 @@ export const getLoginStatus = () => {
* @returns {object} localtion的query对象 * @returns {object} localtion的query对象
*/ */
export const query = () => { export const query = () => {
return Qs.parse(window.location.href.split('?')[1]) return Qs.parse(window.location.href.split("?")[1]);
} };
/** /**
* 编码url参数 * 编码url参数
...@@ -41,8 +40,8 @@ export const query = () => { ...@@ -41,8 +40,8 @@ export const query = () => {
* @returns string * @returns string
*/ */
export const encodeURI = (data) => { export const encodeURI = (data) => {
return Qs.stringify(data, { arrayFormat: 'repeat', allowDots: true }); return Qs.stringify(data, { arrayFormat: "repeat", allowDots: true });
} };
/** /**
* formatterDate * formatterDate
...@@ -51,16 +50,19 @@ export const encodeURI = (data) => { ...@@ -51,16 +50,19 @@ export const encodeURI = (data) => {
* @returns {string} val 解析后的结果 * @returns {string} val 解析后的结果
*/ */
export function formatterDate(time) { export function formatterDate(time) {
if (!time) return ''; if (!time) return "";
let date = new Date(Number(time)); let date = new Date(Number(time));
let Y = date.getFullYear() + '-'; let Y = date.getFullYear() + "-";
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; let M =
let D = panLeft(date.getDate()) + ' '; (date.getMonth() + 1 < 10
let h = panLeft(date.getHours()) + ':'; ? "0" + (date.getMonth() + 1)
let m = panLeft(date.getMinutes()) + ':'; : date.getMonth() + 1) + "-";
let D = panLeft(date.getDate()) + " ";
let h = panLeft(date.getHours()) + ":";
let m = panLeft(date.getMinutes()) + ":";
let s = panLeft(date.getSeconds()); let s = panLeft(date.getSeconds());
return Y + M + D + h + m + s; return Y + M + D + h + m + s;
}; }
/** /**
* formatterDate * formatterDate
* *
...@@ -88,7 +90,7 @@ export function formatterDateDay(datetime) { ...@@ -88,7 +90,7 @@ export function formatterDateDay(datetime) {
return Y + M + D; return Y + M + D;
} }
return datetime; return datetime;
}; }
/** /**
* 当前日期加天数后得到的相应日期 * 当前日期加天数后得到的相应日期
* @param {*} day * @param {*} day
...@@ -114,10 +116,9 @@ function doHandleMonth(month) { ...@@ -114,10 +116,9 @@ function doHandleMonth(month) {
} }
function panLeft(num) { function panLeft(num) {
return num < 10 ? '0' + num : num; return num < 10 ? "0" + num : num;
} }
/** /**
* call方法 * call方法
* *
...@@ -129,23 +130,24 @@ function panLeft(num) { ...@@ -129,23 +130,24 @@ function panLeft(num) {
*/ */
const call = (callMethod, url, formData, config = {}) => { const call = (callMethod, url, formData, config = {}) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
callMethod(url, formData, config).then(res => { callMethod(url, formData, config)
.then((res) => {
const { code, msg, data } = res; const { code, msg, data } = res;
if (code !== 1) { if (code !== 1) {
reject({ reject({
message: msg || '' message: msg || "",
}); });
return; return;
} }
resolve(res); resolve(res);
}) })
.catch(error => { .catch((error) => {
if (error.status === 403) { if (error.status === 403) {
window.location.href = '/#/login' window.location.href = "/#/login";
} }
reject(error); reject(error);
}) });
}) });
}; };
/** /**
...@@ -173,10 +175,10 @@ export const normalCallGet = (url, formData, config = {}) => { ...@@ -173,10 +175,10 @@ export const normalCallGet = (url, formData, config = {}) => {
}; };
const mimeMap = { const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
zip: 'application/zip', zip: "application/zip",
doc: 'application/msword' doc: "application/msword",
} };
/** /**
* 普通的ajax download请求 * 普通的ajax download请求
...@@ -189,90 +191,107 @@ const mimeMap = { ...@@ -189,90 +191,107 @@ const mimeMap = {
export const download = (url, formData, config = {}) => { export const download = (url, formData, config = {}) => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const option = Object.assign({}, config, { const option = Object.assign({}, config, {
responseType: 'blob' responseType: "blob",
}) });
try { try {
const data = await post(url, formData, option) const data = await post(url, formData, option);
const link = document.createElement('a') const link = document.createElement("a");
let blob let blob;
let extName let extName;
if (option.type == "zip") { if (option.type == "zip") {
blob = new Blob([data], { type: mimeMap.zip }) blob = new Blob([data], { type: mimeMap.zip });
extName = "zip" extName = "zip";
} else if (option.type == "excel") { } else if (option.type == "excel") {
blob = new Blob([data], { type: mimeMap.xlsx }) blob = new Blob([data], { type: mimeMap.xlsx });
extName = "xlsx" extName = "xlsx";
} else if (option.type == "doc") { } else if (option.type == "doc") {
blob = new Blob([data], { type: mimeMap.doc }) blob = new Blob([data], { type: mimeMap.doc });
extName = "doc" extName = "doc";
} else { } else {
extName = "xlsx" extName = "xlsx";
} }
let fileName = "导出" let fileName = "导出";
if (option.fileName) { if (option.fileName) {
fileName = option.fileName fileName = option.fileName;
} }
link.href = URL.createObjectURL(blob) link.href = URL.createObjectURL(blob);
link.setAttribute('download', `${fileName}.${extName}`) // 设置下载文件名称 link.setAttribute("download", `${fileName}.${extName}`); // 设置下载文件名称
document.body.appendChild(link) document.body.appendChild(link);
link.click() link.click();
document.body.appendChild(link) document.body.appendChild(link);
resolve(); resolve();
} catch (error) { } catch (error) {
reject(error); reject(error);
} }
}) });
}; };
export const downloadWithCustName = (url, formData, config = {}) => { export const downloadWithCustName = (url, formData, config = {}) => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const option = Object.assign({}, config, { const option = Object.assign({}, config, {
responseType: 'blob', responseType: "blob",
baseURL: '/m', baseURL: "/m",
headers: { headers: {
post: { post: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
} },
} },
}) });
try { try {
const params = Object.assign({}, formData, { const params = Object.assign({}, formData, {
__mortals_token__: cookie.getItem('__mortals_token__'), __mortals_token__: cookie.getItem("__mortals_token__"),
}) });
var requestData = Qs.stringify(params, { arrayFormat: 'repeat', allowDots: true }); var requestData = Qs.stringify(params, {
axios.post(url, requestData, option) arrayFormat: "repeat",
.then(response => { allowDots: true,
if (response.data.type == 'application/json') { });
axios
.post(url, requestData, option)
.then(
(response) => {
if (response.data.type == "application/json") {
var reader = new FileReader(); var reader = new FileReader();
reader.onload = function (event) { reader.onload = function(event) {
var content = reader.result; var content = reader.result;
reject(content); reject(content);
}; };
reader.readAsText(response.data); reader.readAsText(response.data);
return; return;
} }
const filename = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1]) || `${url.substr(1).replace(/\//g, '_')}_${new Date().getTime()}.xls` const filename =
let downloadUrl = window.URL.createObjectURL(new Blob([response.data])) decodeURI(
let link = document.createElement('a') response.headers["content-disposition"]
link.style.display = 'none'; .split(";")[1]
.split("=")[1]
) ||
`${url
.substr(1)
.replace(/\//g, "_")}_${new Date().getTime()}.xls`;
let downloadUrl = window.URL.createObjectURL(
new Blob([response.data])
);
let link = document.createElement("a");
link.style.display = "none";
link.href = downloadUrl; link.href = downloadUrl;
link.setAttribute('download', filename); link.setAttribute("download", filename);
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
document.body.removeChild(link); document.body.removeChild(link);
resolve(); resolve();
}, err => { },
(err) => {
reject(err); reject(err);
}).catch((error) => { }
reject(error) )
}) .catch((error) => {
reject(error);
});
} catch (error) { } catch (error) {
reject(error); reject(error);
} }
}) });
}; };
/** /**
...@@ -306,16 +325,15 @@ export async function getUserListByQuery(query) { ...@@ -306,16 +325,15 @@ export async function getUserListByQuery(query) {
try { try {
/* //下拉只获取正常状态数据:status{0: "停用", 1: "正常", 2: "冻结", 3: "销户", 4: "离职"} /* //下拉只获取正常状态数据:status{0: "停用", 1: "正常", 2: "冻结", 3: "销户", 4: "离职"}
query["query.status"] = 1;*/ query["query.status"] = 1;*/
const data = await normalCallPost('/user/list', query); const data = await normalCallPost("/user/list", query);
const list = data.data.result.map(({ id, loginName, realName, mobile }) => { const list = data.data.result.map(({ id, loginName, realName, mobile }) => {
return { id, loginName, realName, mobile } return { id, loginName, realName, mobile };
}); });
return list; return list;
} catch (error) { } catch (error) {
return []; return [];
} }
}; }
/** /**
* 构造树型结构数据 * 构造树型结构数据
...@@ -326,27 +344,34 @@ export async function getUserListByQuery(query) { ...@@ -326,27 +344,34 @@ export async function getUserListByQuery(query) {
* @param {*} rootId 根Id 默认 0 * @param {*} rootId 根Id 默认 0
*/ */
export function handleTree(data, id, parentId, children, rootId) { export function handleTree(data, id, parentId, children, rootId) {
id = id || 'id' id = id || "id";
parentId = parentId || 'parentId' parentId = parentId || "parentId";
children = children || 'children' children = children || "children";
rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0 rootId =
rootId ||
Math.min.apply(
Math,
data.map((item) => {
return item[parentId];
})
) ||
0;
//对源数据深度克隆 //对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data)) const cloneData = JSON.parse(JSON.stringify(data));
//循环所有项 //循环所有项
console.log("11111", cloneData) console.log("11111", cloneData);
const treeData = cloneData.filter(father => { const treeData = cloneData.filter((father) => {
let branchArr = cloneData.filter(child => { let branchArr = cloneData.filter((child) => {
//返回每一项的子级数组 //返回每一项的子级数组
return father[id] === child[parentId] return father[id] === child[parentId];
}); });
branchArr.length > 0 ? father.children = branchArr : ''; branchArr.length > 0 ? (father.children = branchArr) : "";
//返回第一层 //返回第一层
return father[parentId] === rootId; return father[parentId] === rootId;
}); });
console.log("treeData", treeData) console.log("treeData", treeData);
return treeData != '' ? treeData : data; return treeData != "" ? treeData : data;
}; }
/** /**
* 下载文件 * 下载文件
...@@ -359,7 +384,7 @@ export function downloadFile(path, name) { ...@@ -359,7 +384,7 @@ export function downloadFile(path, name) {
xhr.open("get", path); xhr.open("get", path);
xhr.responseType = "blob"; xhr.responseType = "blob";
xhr.send(); xhr.send();
xhr.onload = function () { xhr.onload = function() {
if (this.status === 200 || this.status === 304) { if (this.status === 200 || this.status === 304) {
// 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
if ("msSaveOrOpenBlob" in navigator) { if ("msSaveOrOpenBlob" in navigator) {
...@@ -380,10 +405,8 @@ export function downloadFile(path, name) { ...@@ -380,10 +405,8 @@ export function downloadFile(path, name) {
} }
}; };
} }
} }
// 当元素滚动条被滚动时运行的脚本 // 当元素滚动条被滚动时运行的脚本
export function handleScroll() { export function handleScroll() {
let scrollbarEl = this.$refs["scroll"].wrap; let scrollbarEl = this.$refs["scroll"].wrap;
...@@ -442,13 +465,4 @@ export function jump(index) { ...@@ -442,13 +465,4 @@ export function jump(index) {
_this.$refs["scroll"].wrap.scrollTop = distance; _this.$refs["scroll"].wrap.scrollTop = distance;
} }
} }
}; }
import axios from 'axios'; import axios from "axios";
import Qs from 'qs'; import Qs from "qs";
import cookie from './cookie'; import cookie from "./cookie";
import httpErrorHandler from './httpErrorHandler'; import httpErrorHandler from "./httpErrorHandler";
const isDev = process.env.NODE_ENV === 'development'; const isDev = process.env.NODE_ENV === "development";
const queue = []; const queue = [];
const cancelToken = axios.CancelToken; const cancelToken = axios.CancelToken;
const token = (config) =>{ const token = (config) => {
return `${config.url}_${config.method}` return `${config.url}_${config.method}`;
} };
const instance = axios.create({ const instance = axios.create({
baseURL: '/m', baseURL: "/m",
headers: { headers: {
token: cookie.getItem('fe_t'), token: cookie.getItem("fe_t"),
post: { post: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
'dataType': 'json', dataType: "json",
} },
} },
}); });
const removeQueue = (config) => { const removeQueue = (config) => {
for(let i=0, size = queue.length; i < size; i++){ for (let i = 0, size = queue.length; i < size; i++) {
const task = queue[i]; const task = queue[i];
if(task.token === token(config)) { if (task.token === token(config)) {
task.cancel(); task.cancel();
queue.splice(i, 1); queue.splice(i, 1);
} }
} }
} };
//添加请求拦截器 //添加请求拦截器
instance.interceptors.request.use(config=>{ instance.interceptors.request.use(
(config) => {
removeQueue(config); //在一个ajax发送前执行一下取消操作 removeQueue(config); //在一个ajax发送前执行一下取消操作
config.cancelToken = new cancelToken((c)=>{ config.cancelToken = new cancelToken((c) => {
queue.push({ token: token(config), cancel: c }); queue.push({ token: token(config), cancel: c });
}); });
return config; return config;
}, error => { },
(error) => {
return Promise.reject(error); return Promise.reject(error);
}); }
);
//添加响应拦截器 //添加响应拦截器
instance.interceptors.response.use(response=>{ instance.interceptors.response.use((response) => {
removeQueue(response.config); removeQueue(response.config);
return response.data return response.data;
}, httpErrorHandler); }, httpErrorHandler);
/** /**
...@@ -56,5 +59,5 @@ instance.interceptors.response.use(response=>{ ...@@ -56,5 +59,5 @@ instance.interceptors.response.use(response=>{
* @returns * @returns
*/ */
export default (url, data, config = {}) => { export default (url, data, config = {}) => {
return instance.post(url, data, config) return instance.post(url, data, config);
} };
...@@ -202,7 +202,6 @@ export default { ...@@ -202,7 +202,6 @@ export default {
emit() { emit() {
this.$emit("input", this.newVal); this.$emit("input", this.newVal);
this.$emit("change", this.newVal); this.$emit("change", this.newVal);
console.log(this.newVal);
}, },
}, },
computed: { computed: {
......
...@@ -103,8 +103,6 @@ export default { ...@@ -103,8 +103,6 @@ export default {
}, },
beforeSubmit(data) { beforeSubmit(data) {
data.companyIds = data.companyIds.join(",");
return data; return data;
}, },
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment