uni-app 笔记

应用生命周期

onLaunch 当uni-app 初始化完成时触发(全局只触发一次)
onShow 当 uni-app 启动,或从后台进入前台显示
onHide 当 uni-app 从前台进入后台

页面生命周期

onLoad 监听页面加载,其参数为上个页面传递的数据,参数类型为Object(用于页面传参 onShow 监听页面显示

onReady 监听页面初次渲染完成

onHide 监听页面隐藏

onUnload 监听页面卸载

onPullDownRefresh 监听用户下拉动作 ,一般用于下拉刷新

onReachBottom 页面上拉触底事件的处理函数

onPageScroll 监听页面滚动 ,参数为 Object

onTabItemTap 当前是 tab 页时,点击 tab 时触发。

onShareAppMessage 用户点击右上角分享

  • 先触发 uni-app onReady ,后触发 vuemounted
  • 建议使用uni-apponLoad 代替 vuecreated

publicPath 未生效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<image class="logo" src="../../static/logo.png"></image>
需要这样来写
<image class="logo" :src="require('../../static/logo.png')"></image>

或webpack
module.exports = {
chainWebpack(webpackConfig) {
webpackConfig.module
.rule('vue')
.test([/\.vue$/, /\.nvue$/])
.use('vue-loader')
.tap(options => Object.assign(options, {
transformAssetUrls: {
'v-uni-image': 'src'
}
}))
.end()
},

configureWebpack (config) {
// ...blablabla
},
}

uni.getStorageSync && uni.getStorage经常获取不到值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try {
const userInfo = uni.getStorageSync('userInfo');
if(userInfo){
// do
}
}catch(e){
//error
}


uni.getStorage({
key: 'userInfo',
success: function (res) {
console.log(res.data);
that.seal=res.data
}
});

store 设计思路

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
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
state: {
hasLogin: false,
token:'',
userInfo: {}
},
mutations: {
login(state, provider) {
uni.setStorage({//缓存用户token
key: 'token',
data: provider
})
},
userInfo(state, provider){
state.hasLogin = true;
uni.setStorage({//缓存用户登陆状态
key: 'userInfo',
data: provider
})
},
logout(state) {
state.hasLogin = false;
state.userInfo = {};
state.token = '';
uni.removeStorage({
key: 'userInfo'
})
uni.removeStorage({
key: 'token'
})
uni.reLaunch({
url:'/pages/login/login'
})
}
},
actions: {

}
})
export default store

$http封装思路

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
// config.js
import request from "./request";
// 全局配置的请求域名
let baseUrl = "http://localhost:8762";
//可以new多个request来支持多个域名请求
let $http = new request({
//接口请求地址
baseUrl: baseUrl,
//服务器本地上传文件地址
fileUrl: baseUrl,
//设置请求头(如果使用报错跨域问题,可能是content-type请求类型和后台那边设置的不一致)
header: {
'content-type': 'application/json;charset=UTF-8'
},
//以下是默认值可不写
//是否提示--默认提示
isPrompt: true,
//是否显示请求动画
load: true,
//是否使用处理数据模板
isFactory: true
});

//当前接口请求数
let requestNum = 0;
//请求开始拦截器
$http.requestStart = function(options) {
if (options.load) {
if (requestNum <= 0) {
//打开加载动画
uni.showLoading({
title: '加载中',
mask: true
});
}
requestNum += 1;
}
// 图片上传大小限制
if (options.method == "FILE" && options.maxSize) {
// 文件最大字节: options.maxSize 可以在调用方法的时候加入参数
maxSize = options.maxSize;
for (let item of options.files) {
if (item.size > maxSize) {
setTimeout(() => {
uni.showToast({
title: "图片过大,请重新上传",
icon: "none"
});
}, 500);
return false;
}
}
}
//请求前加入token
options.header['token'] = "1234568";
return options;
}
//请求结束
$http.requestEnd = function(options, resolve) {
//判断当前接口是否需要加载动画
if (options.load) {
requestNum = requestNum - 1;
if (requestNum <= 0) {
uni.hideLoading();
}
}
if (resolve.errMsg && resolve.statusCode && resolve.statusCode > 300) {
setTimeout(() => {
uni.showToast({
title: "网络错误,请检查一下网络",
icon: "none"
});
}, 500);
}
}
//登录弹窗次数
let loginPopupNum = 0;
//所有接口数据处理(可在接口里设置不调用此方法)
//此方法需要开发者根据各自的接口返回类型修改,以下只是模板
$http.dataFactory = function(res) {
// 判断接口请求是否成功
if (res.response.statusCode && res.response.statusCode == 200) {
let httpData = res.response.data;

/*********以下只是模板(及共参考),需要开发者根据各自的接口返回类型修改*********/
//判断数据是否请求成功
if (httpData.success) {
// 返回正确的结果(then接受数据)
res.resolve(httpData);
} else { //其他错误提示
if (res.isPrompt) { //设置可以提示的时候
setTimeout(function() {
uni.showToast({
title: httpData.msg, //提示后台接口抛出的错误信息
icon: "none",
duration: 3000
});
}, 500);
}
// 返回错误的结果(catch接受数据)
res.reject(res.response);
}
/*********以上只是模板(及共参考),需要开发者根据各自的接口返回类型修改*********/

} else {
// 返回错误的结果(catch接受数据)
res.reject(res.response);
}
};
export default $http;
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
//request.js
export default class request {
constructor(options) {
//请求公共地址
this.baseUrl = options.baseUrl || "";
//公共文件上传请求地址
this.fileUrl = options.fileUrl || "";
//默认请求头
this.header = options.header || {};
//默认配置
this.config = {
isPrompt: options.isPrompt === false ? false : true,
load: options.load === false ? false : true,
isFactory: options.isFactory === false ? false : true,
loadMore: options.loadMore === false ? false : true
};
}

// 获取默认信息
getDefault(data, options = {}) {
//判断url是不是链接
let urlType = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~/])+$/.test(data.url);
let config = Object.assign({}, this.config, options, data);
if (data.method == "FILE") {
config.url = urlType ? data.url : this.fileUrl + data.url;
} else {
config.url = urlType ? data.url : this.baseUrl + data.url;
}
//请求头
if (options.header) {
config.header = Object.assign({}, this.header, options.header);
} else if (data.header) {
config.header = Object.assign({}, this.header, data.header);
} else {
config.header = this.header;
}
return config;
}

//post请求
post(url = '', data = {}, options = {}) {
return this.request({
method: "POST",
data: data,
url: url,
...options
});
}

//get请求
get(url = '', data = {}, options = {}) {
return this.request({
method: "GET",
data: data,
url: url,
...options
});
}

//put请求
put(url = '', data = {}, options = {}) {
return this.request({
method: "PUT",
data: data,
url: url,
...options
});
}

//delete请求
delete(url = '', data = {}, options = {}) {
return this.request({
method: "DELETE",
data: data,
url: url,
...options
});
}

//接口请求方法
request(data) {
return new Promise((resolve, reject) => {
if (!data.url) {
console.log("request缺失数据url");
reject({
errMsg: "缺失数据url",
statusCode: 0
});
return;
}
let requestInfo = this.getDefault(data);
//请求前回调
if (this.requestStart) {
let requestStart = this.requestStart(requestInfo);
if (typeof requestStart == "object") {
requestInfo.data = requestStart.data;
requestInfo.header = requestStart.header;
requestInfo.isPrompt = requestStart.isPrompt;
requestInfo.load = requestStart.load;
requestInfo.isFactory = requestStart.isFactory;
} else {
//请求完成回调
_this.requestEnd && _this.requestEnd(requestInfo, {
errMsg: "请求开始拦截器未通过",
statusCode: 0
});
reject({
errMsg: "请求开始拦截器未通过",
statusCode: 0
});
return;
}
}
let requestData = {
url: requestInfo.url,
header: requestInfo.header, //加入请求头
success: (res) => {
//请求完成回调
this.requestEnd && this.requestEnd(requestInfo, res);
//是否用外部的数据处理方法
if (requestInfo.isFactory && this.dataFactory) {
//数据处理
this.dataFactory({
...requestInfo,
response: res,
resolve: resolve,
reject: reject
});
} else {
resolve(res);
}
},
fail: (err) => {
console.log("err");
//请求完成回调
this.requestEnd && this.requestEnd(requestInfo, err);
reject(err);
}
};
//请求类型
if (requestInfo.method) {
requestData.method = requestInfo.method;
}
if (requestInfo.data) {
requestData.data = requestInfo.data;
}
// #ifdef MP-WEIXIN || MP-ALIPAY
if (requestInfo.timeout) {
requestData.timeout = requestInfo.timeout;
}
// #endif
if (requestInfo.dataType) {
requestData.dataType = requestInfo.dataType;
}
// #ifndef APP-PLUS || MP-ALIPAY
if (requestInfo.responseType) {
requestData.responseType = requestInfo.responseType;
}
// #endif
// #ifdef H5
if (requestInfo.withCredentials) {
requestData.withCredentials = requestInfo.withCredentials;
}
// #endif
uni.request(requestData);
});
}
//jsonp请求(只限于H5使用)
jsonp(url = '', data = {}, options = {}) {
let requestInfo = this.getDefault({
method: "JSONP",
data: data,
url: url,
}, options);
let dataStr = '';
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&';
});
//匹配最后一个&并去除
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
}
requestInfo.url = requestInfo.url + '?' + dataStr;
const _this = this;
return new Promise((resolve, reject) => {
let callbackName = "callback" + Math.ceil(Math.random() * 1000000);
if (_this.requestStart) {
requestInfo.data = data;
let requestStart = _this.requestStart(requestInfo);
if (typeof requestStart == "object") {
requestInfo.data = requestStart.data;
requestInfo.header = requestStart.header;
requestInfo.isPrompt = requestStart.isPrompt;
requestInfo.load = requestStart.load;
requestInfo.isFactory = requestStart.isFactory;
} else {
//请求完成回调
_this.requestEnd && _this.requestEnd(requestInfo, {
errMsg: "请求开始拦截器未通过",
statusCode: 0
});
reject({
errMsg: "请求开始拦截器未通过",
statusCode: 0
});
return;
}
}
// #ifdef H5
window[callbackName] = function(data) {
resolve(data);
}
let script = document.createElement("script");
script.src = requestInfo.url + "&callback=" + callbackName;
document.head.appendChild(script);
// 及时删除,防止加载过多的JS
document.head.removeChild(script);
// #endif
//请求完成回调
_this.requestEnd && _this.requestEnd(requestInfo, {
errMsg: "request:ok",
statusCode: 200
});
});
}
}