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

时间:2022-03-26 15:04:44

步骤:

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

部分代码:

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

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

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

2.引入文件:

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

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

1、公共插件

实现目标,将公共组件或者网络请求直接在this中调用,不需要再页面引用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#例如网络请求
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 封装成对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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 文件中将工具注册进入

?
1
2
3
4
5
6
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中封装方法以及多处引用该方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/baoyingltt/article/details/82771464