在vue中封裝方法以及多處引用該方法詳解
步驟:
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 = falseVue.prototype.utils = utilsVue.prototype.api = api
以上這篇在vue中封裝方法以及多處引用該方法詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
