在vue中封裝方法以及多處引用該方法詳解
步驟:
1.先建立一個文件,放你想封裝的方法;然后導(dǎo)出;
部分代碼:
注: 導(dǎo)出這個地方需要特別注意:如果是一個對象的話:export 對象;如果是一個函數(shù)的話:export { 函數(shù) }
2.引入文件:
補(bǔ)充知識:vue uni-app 公共組件封裝,防止每個頁面重復(fù)導(dǎo)入
1、公共插件
實現(xiàn)目標(biāo),將公共組件或者網(wǎng)絡(luò)請求直接在this中調(diào)用,不需要再頁面引用
#例如網(wǎng)絡(luò)請求var _this = this; this.api.userInfo({ token: ’’ } #通用工具_(dá)this.utils.showBoxFunNot('是否退出登陸', function() { console.log('確定') _this.api.logOut({}, function(data) { _this.utils.setCacheValue(’token’, ’’) uni.redirectTo({ url: ’/pages/LogIn/LogIn’ }); }) })
公共插件utils.js 或者可以將網(wǎng)絡(luò)請求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 = ’參數(shù)不能為空’) { 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('為空的參數(shù):',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 文件中將工具注冊進(jìn)入
import utils from ’common/utils.js’;import api from ’common/api.js’;Vue.config.productionTip = falseVue.prototype.utils = utilsVue.prototype.api = api
以上這篇在vue中封裝方法以及多處引用該方法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP設(shè)計模式中工廠模式深入詳解2. 得到XML文檔大小的方法3. ASP實現(xiàn)加法驗證碼4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. ASP基礎(chǔ)知識Command對象講解6. jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進(jìn))7. 詳細(xì)分析css float 屬性以及position:absolute 的區(qū)別8. PHP循環(huán)與分支知識點梳理9. PHP session反序列化漏洞超詳細(xì)講解10. html小技巧之td,div標(biāo)簽里內(nèi)容不換行
