vue-组件

vue上传

template的模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<el-input v-model="formLabelAlign.filename"></el-input> 
<el-upload
class="upload-demo"
ref="upload"
:action="action"
:http-request="beforeAvatarUpload"
:limit="1"
:on-exceed="handleExceed"
:multiple="false"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" icon="el-icon-upload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
</el-upload>

methods里面的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 文件上传数量超过Limit限制
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1个文件`);
},
// 上传文件
beforeAvatarUpload(fileObj) {
// const isJPG = file.type === 'image/jpeg';
// const isGIF = file.type === 'image/gif';
// const isPNG = file.type === 'image/png';
// const isBMP = file.type === 'image/bmp';

// const isCSV = file.type === ".csv"
// const isXLS = file.type === "application/vnd.ms-excel"
// const isXLSX = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
// console.log( file.type );
// const isLt2M = file.size / 1024 / 1024 < 2;
//
// if (!isCSV || !isXLS || !isXLSX) {
// this.$message.error("上传头像图片只能是 Excels格式!");
// }
// if (!isLt2M) {
// this.$message.error("上传头像图片大小不能超过 2MB!");
// }
// return isCSV || isXLS || isXLSX && isLt2M;

let formData = new FormData(); // 声明一个FormData对象
formData.append('name', fileObj.file.name)
formData.append('file', fileObj.file)
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post(this.action, formData, config).then((res) => {
if(res.data.status){
this.formLabelAlign.filename = res.data.data;
this.$message.success("上传成功!");
}else{
this.$message.error("上传失败!");
}

}) ; // 发送请求

},
// 提交上传数据
submitUpload (){
this.$refs.upload.submit() ;
console.log("sdfs") ;
},

axios 使用

请求头设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import axios from 'axios' //引用axios
import {getCookie} from './util' //引用刚才我们创建的util.js文件,并使用getCookie方法

// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'http://192.168.73.61:5000/'; //这是调用数据接口

// http request 拦截器,通过这个,我们就可以把Cookie传到后台
axios.interceptors.request.use(
config => {
const token = getCookie('session'); //获取Cookie
// config.data = JSON.stringify(config.data);
if (token) {
config.headers = {
"Content-Type": "application/json; charset=UTF-8", //设置跨域头部
"Authorization": token ,
};
}
return config;
},
err => {
return Promise.reject(err);
}
);


// http response 拦截器
axios.interceptors.response.use(
response => {
//response.data.errCode是我接口返回的值,如果值为2,说明Cookie丢失,然后跳转到登录页,这里根据大家自己的情况来设定
// if(response.data.errCode == 2) {
// router.push({
// path: '/login',
// query: {redirect: router.currentRoute.fullPath} //从哪个页面跳转
// })
// }
return response;
},
error => {
return Promise.reject(error.response.data)
});

export default axios;

/**
* fetch 请求方法
* @param url
* @param params
* @returns {Promise}
*/
export function fetch(url, params = {}) {

return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then(response => {
resolve(response.data);
})
.catch(err => {
reject(err)
})
})
}

/**
* post 请求方法
* @param url
* @param data
* @returns {Promise}
*/
export function post(url, data = {}) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err);
})
})
}

/**
* patch 方法封装
* @param url
* @param data
* @returns {Promise}
*/
export function patch(url, data = {}) {
return new Promise((resolve, reject) => {
axios.patch(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err);
})
})
}

/**
* put 方法封装
* @param url
* @param data
* @returns {Promise}
*/
export function put(url, data = {}) {
return new Promise((resolve, reject) => {
axios.put(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err);
})
})
}

axios多并发访问

1
2
3
4
5
6
7
8
发送并发请求
axios
.all([axios.get('/profile'), axios.post('/user')])
.then(axios.spread((res1, res2)=>{
console.log(res1)
console.log(res2)
}))
axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

axios请求配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{
// 请求地址
url: '/user',
// 请求类型
method: 'get',
// 请根路径
baseURL: 'http://www.mt.com/api',
// 请求前的数据处理
transformRequest:[function(data){}],
// 请求后的数据处理
transformResponse: [function(data){}],
// 自定义的请求头
headers:{'x-Requested-With':'XMLHttpRequest'},
// URL查询对象
params:{ id: 12 },
// 查询对象序列化函数
paramsSerializer: function(params){ }
// request body
data: { key: 'aa'},
// 超时设置s
timeout: 1000,
// 跨域是否带Token
withCredentials: false,
// 自定义请求处理
adapter: function(resolve, reject, config){},
// 身份验证信息
auth: { uname: '', pwd: '12'},
// 响应的数据格式 json / blob /document /arraybuffer / text / stream
responseType: 'json',

// xsrf 设置
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',

// 下传和下载进度回调
onUploadProgress: function(progressEvent){
Math.round( (progressEvent.loaded * 100) / progressEvent.total )
},
onDownloadProgress: function(progressEvent){},

// 最多转发数,用于node.js
maxRedirects: 5,

// 最大响应数据大小
maxContentLength: 2000,
// 自定义错误状态码范围
validateStatus: function(status){
return status >= 200 && status < 300;
},
// 用于node.js
httpAgent: new http.Agent({ keepAlive: treu }),
httpsAgent: new https.Agent({ keepAlive: true }),

// 用于设置跨域请求代理
proxy: {
host: '127.0.0.1',
port: 8080,
auth: {
username: 'aa',
password: '2123'
}
},
// 用于取消请求
cancelToken: new CancelToken(function(cancel){})
}

全局配置

1
2
axios.defaults.baseURL = ‘http://www.xx.com/api'
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;

其它

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import axios from 'axios'
import store from '@/store';

// axios.defaults.headers.post["Content-Type"] = "application/json; charset=UTF-8" ;
// axios.defaults.timeout = 5000 ; //响应时间
// axios.defaults.baseURL = "http://192.168.76.16:5000/" ; //配置接口地址
// axios.defaults.headers.common["Authorization"] = store.state.token ;

// 请求拦截器
axios.interceptors.request.use(function(config) {
return config;
}, function(error) {
return Promise.reject(error);
})


// 响应拦截器
axios.interceptors.response.use(function(response) {
return response;
}, function(error) {
return Promise.reject(error);
})


// 封装axios的post请求--同步请求
export function fetchPOST(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}


// 封装axios的get请求--同步请求
export function fetchGET(url, params) {
return new Promise((resolve, reject) => {
axios.get(url, params)
.then(response => {
resolve(response);
})
.catch((error) => {
reject(error);
})
})
}


export default {
secPost(url, params) {
// console.log(url,params,"POST");
return fetchPOST(url, params);
},
secGet(url, params) {
// console.log(url,params,"GET");
return fetchGET(url, params);
}
}

cookie设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//获取cookie、
export function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return (arr[2]);
else
return null;
}

//设置cookie,增加到vue实例方便全局调用
export function setCookie (c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
};

//删除cookie
export function delCookie (name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};
坚持原创技术分享,您的支持将鼓励我继续创作!