uni-app全局属性和方法


全局变量和全局方法是软件开发中常用的技术点!

实现方式大致分为:

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM