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