1.公共插件
实现目标,将公共组件或者网络请求直接在this中调用,不需要再页面引用
#例如网络请求
var _this = this;
this.api.userInfo({
token: ''
}
#通用工具
_this.utils.showBoxFunNot("是否退出登陆", function() {
console.log("确定")
_this.api.logOut({}, function(data) {
_this.utils.setCacheValue('token', '')
uni.redirectTo({
url: '/pages/LogIn/LogIn'
});
})
})
公共插件utils.js 或者可以将网络请求api.js 封装成对象
var utils = {
function_chk: function(f) {
try {
var fn = eval(f);
if (typeof(fn) === 'function') {
return true;
} else {
return false;
}
} catch (e) {
}
return false;
},
showBox: function(msg) {
uni.showModal({
title: "错误提示",
content: "" + msg,
showCancel: false,
confirmText: "确定"
})
},
showBoxFun: function(msg, fun) {
uni.showModal({
title: "提示",
content: "" + msg,
showCancel: false,
confirmText: "确定",
success: (res) => {
fun(res)
}
})
},
showBoxFunNot: function(msg, fun, cancel) {
var _this = this
uni.showModal({
title: "提示",
content: "" + msg,
confirmText: "确定",
cancelText: "取消",
success: (res) => {
if (res.confirm) { //取消
if (_this.function_chk(fun)) {
fun(res)
}
} else if (res.cancel) { //确定
if (_this.function_chk(cancel)) {
cancel(res)
}
}
},
can: (err) => {
}
})
},
notNull: function(obj, msg = '参数不能为空') {
var keys = Object.keys(obj);
console.log(keys)
for (var i in keys) {
var keyName = keys[i]
console.log(keys[i])
var value = obj[keyName]
if (value == '') {
console.log("为空的参数:",keyName)
this.showBox(msg)
return true;
}
console.log(value)
}
return false;
},
getCacheValue: function(key) {
var value = '';
try {
value = uni.getStorageSync(key);
} catch (e) {
}
return value;
},
setCacheValue: function(key, value) {
try {
value = uni.setStorageSync(key, value);
} catch (e) {
}
}
}
export default utils
2.注册到vue 实例中
main.js 文件中将工具注册进入
import utils from 'common/utils.js';
import api from 'common/api.js';
Vue.config.productionTip = false
Vue.prototype.utils = utils
Vue.prototype.api = api