1. 程式人生 > 程式設計 >在vue中封裝方法以及多處引用該方法詳解

在vue中封裝方法以及多處引用該方法詳解

步驟:

1.先建立一個檔案,放你想封裝的方法;然後匯出;

部分程式碼:

在vue中封裝方法以及多處引用該方法詳解

在vue中封裝方法以及多處引用該方法詳解

注: 匯出這個地方需要特別注意:如果是一個物件的話:export 物件;如果是一個函式的話:export { 函式 }

2.引入檔案:

在vue中封裝方法以及多處引用該方法詳解

補充知識: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: "提示",confirmText: "確定",success: (res) => {
 fun(res)
 }
 })

 },showBoxFunNot: function(msg,fun,cancel) {
 var _this = this
 uni.showModal({
 title: "提示",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中封裝方法以及多處引用該方法詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。