您的位置:首页 > Web前端 > Vue.js

在vue中封装方法以及多处引用该方法详解

2020-08-15 04:08 1146 查看

步骤:

1.先建立一个文件,放你想封装的方法;然后导出;

部分代码:

注: 导出这个地方需要特别注意:如果是一个对象的话:export 对象;如果是一个函数的话:export { 函数 }

2.引入文件:

补充知识:vue uni-app 公共组件封装,防止每个页面重复导入

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

以上这篇在vue中封装方法以及多处引用该方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue 封装