在vue中封裝方法以及多處引用該方法詳解
步驟:
1.先建立一個(gè)文件,放你想封裝的方法;然后導(dǎo)出;
部分代碼:
注: 導(dǎo)出這個(gè)地方需要特別注意:如果是一個(gè)對(duì)象的話:export 對(duì)象;如果是一個(gè)函數(shù)的話:export { 函數(shù) }
2.引入文件:
補(bǔ)充知識(shí):vue uni-app 公共組件封裝,防止每個(gè)頁(yè)面重復(fù)導(dǎo)入
1、公共插件
實(shí)現(xiàn)目標(biāo),將公共組件或者網(wǎng)絡(luò)請(qǐng)求直接在this中調(diào)用,不需要再頁(yè)面引用
#例如網(wǎng)絡(luò)請(qǐng)求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ò)請(qǐng)求api.js 封裝成對(duì)象
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: '錯(cuò)誤提示', 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、注冊(cè)到vue 實(shí)例中
main.js 文件中將工具注冊(cè)進(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中封裝方法以及多處引用該方法詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 父div高度不能自適應(yīng)子div高度的解決方案2. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法3. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)4. JSP狀態(tài)管理的簡(jiǎn)單介紹5. jsp+mysql實(shí)現(xiàn)網(wǎng)頁(yè)的分頁(yè)查詢6. servlet+jsp實(shí)現(xiàn)過(guò)濾器 防止用戶未登錄訪問(wèn)7. 選擇模式 - XSL教程 - 28. Java之JSP教程九大內(nèi)置對(duì)象詳解(中篇)9. 淺談XML Schema中的elementFormDefault屬性10. ASP中SELECT下拉菜單同時(shí)獲取VALUE和TEXT值的實(shí)現(xiàn)代碼
