一、背景
在釘釘小程序裏面使用methods定義了一個方法A,在方法B中想要使用方法A裏面得到的值
例如定義了方法A,方法A可以獲取storage緩存,又定義了方法B,方法B調A拿到緩存後使用緩存裏面的數據去請求一個接口,那麼如何實現?
二、解決方法
1、通過一個全局變量傳遞
方法B:
scan() {
my.scan({
scanType: ['qrCode', 'barCode'],
success: (res) => {
my.confirm({
// title: '溫馨提示',
content: res.code + '\n將該設備歸檔到自己名下?',
confirmButtonText: '確認',
cancelButtonText: '取消',
success: (result) => {
if (result.confirm == true) {
this.getStorage("userInfo");
var searchUrl = this.data.baseUrl + '/beauty/updateMobileInfo?owner=' + this.data.userId + '&mobileNo=' + res.code;
this.getRequest(searchUrl);
this.getMobileListData(this.data.baseUrl + "/beauty/getMobile");
} else if (result.confirm == false) {
console.log("用戶已取消" + result.confirm)
}
}
});
},
});
}
方法A:
//獲取用戶緩存信息
getStorage: function (key) {
dd.getStorage({
key: key,
success: (res) => {
this.data.userId = res.data.userId
},
fail: function (res) {
dd.alert({ content: res.errorMessage });
}
});
}
公共部分:
Component({
keyWord: {},
data: { baseUrl: "http://localhost:8081", name: "", userId: "" },
//storageData:{name:"",userId:""},
didMount() {
var allMobileInfoUrl = this.data.baseUrl + '/beauty/getMobile';
console.log("===========" + allMobileInfoUrl)
this.getMobileListData(allMobileInfoUrl)
},
methods: {}})
分析:
先調用A的getStorag方法,此方法將緩存中的userId賦值給全局變量userId
再在B裏面調用完A後(this.getstorage)發起http請求,請求參數取的全局變量userId
注意:
在A的getStorage方法中想將dd.getStorage中的res結果賦值給全局變量時候,使用this.data.userId=res.data.userId程序總說data是undefined,因爲在dd.getStorage()函數裏面無法訪問到全局變量,解決方法,使用箭頭函數:success: (res) => {
this.data.userId = res.data.userId
}
官方的寫法:success: function() {
dd.alert({content: ‘寫入成功’});
},不能在success裏面賦值給全局變量
2、使用函數返回值
官方給的這種方法可見可以直接拿到緩存的返回值,就可以直接在方法A中調用了。
let res = dd.getStorageSync({ key: ‘currentCity’ });
dd.alert({
content: JSON.stringify(res.data),
});
但弊端是這個是異步的方法,而我們需要即時拿到緩存數據去發起請求,不能異步,否則不準確。