|
全局变量和全局方法是软件开发中常用的技术点!
实现方式大致分为:
1、vuex实现,值变动灵活
2、建立js文件,页面内引用
3、挂载vue实例后使用
4、小程序中的globalData
5、本地存储
这里简单讲解下uni-app中挂载到vue实例的全局属性和方法:
在Main.js中创建:
Vue.prototype.$httpUrl = "https://xxx/";
//获取图片路径
Vue.prototype.getImgSrc = function(src){
var imgServer = "/pages/static/image/"
// #ifdef MP
imgServer = "https://xxx/";
// #endif
return imgServer + src ;
}
//提示
const tipMsg =(title,icon,time,mask)=>{
title = title == undefined ? "系统繁忙" : title;
icon = icon == undefined ? "none" : icon;
time = time == undefined ? 1500 : time;
mask = mask == undefined ? true : mask;
uni.showToast({
title:title,
icon:icon,
mask:mask,
duration:time
})
}
//验证手机号
const checkPhone = phone=>{
if(!(/^1[23456789]\d{9}$/.test(phone))){
uni.showToast({
title:"手机号格式不正确",
icon:'none'
})
return false;
}
return true;
}
Vue.prototype.$uniApi={tipMsg,checkPhone};
在index.vue中使用:
onLoad() {
var _self = this;
console.log(_self.$httpUrl);
console.log(_self.getImgSrc("home/bg.png"));
_self.$uniApi.checkPhone("12345678910");
_self.$uniApi.tipMsg("听说你比我帅");
}
uni-app更多全局属性设定参考:https://ask.dcloud.net.cn/article/35021
有人住高楼,有人处深沟。
有人光万丈,有人一生绣。
时光是匆匆,回首无旧梦。
人生若几何,凡尘事非多。
深情总遗却,妄自也洒脱。
来源:https://www.cnblogs.com/nanyang520/p/12066479.html |