大家都知道組件很好用,很多情況下我們會用到組件,比如很多小程序有用到 **“諮詢”這個功能,這個功能需要在每個tarBar頁面都有入口文件,那麼問題就來了,我們這個諮詢如果是有用到圖片和文字需要用到接口的時候,我們第一時間會想到能不能在組件上調用接口,這樣的話我們就不需要在每個頁面再次請求接口,增加工作量。那麼,能在組件上調用接口嗎?當然是可以的拉,因爲組件也有他的生命週期,代碼如下:
const network = require("…/…/resource/js/network.js") //封裝的接口
Component({
lifetimes: {
attached: function() {
// 在組件實例進入頁面節點樹時執行
let that = this
// 獲取頁面
network.requests({
url: “homepage”,
data: {
to_uid: “1026”,
user_id: “1026”
},
method: “POST”,
successF: function(res) {
that.setData({
cardInfo: res.data.data.head
})
}
})
},
detached: function() {
// 在組件實例被從頁面節點樹移除時執行
},
},
/
* 組件的屬性列表
*/
properties: {},
// 組件的初始數據
data: {
cardInfo: []
}
......
})
- 1
- 2
這樣就已經在組件請求接口完成了,當然這有個弊端,接口的重複的請求會影響性能,而我們做前端的必須要考慮到用戶體驗感,因此也就引出了——緩存這個概念。由字面上就可以理解,我們請求一個接口,然後將自己需要的數據緩存到本地,然後需要的話就只需要調用本地存儲,這樣就沒有那麼多HTTP請求了。
好了,那麼看下緩存的代碼吧:
home.js代碼
getHome: function(e) {
let that = this
// 獲取頁面
network.requests({//已封裝的接口,相當於wx.request()
url: “homepage”,
data: {
to_uid: “1026”,
user_id: “1026”
},
method: “POST”,
successF: function(res) {
wx.setStorageSync(“consultHead”, res.data.data.head);//儲存數據
// console.log(res.data.data)
that.setData({
pageTem: res.data.data,
cardInfo: res.data.data.head
})
}
})
}
組件中獲取數據:
Component({
lifetimes: {
ready: function () {//頁面加載完成在獲取本地存儲
var K = wx.getStorageSync(“consultHead”)
this.setData({
cardInfo: K
})
},
},
/**
- 組件的屬性列表
*/
properties: {
cardInfo:{//接收父組件傳過的參數
type:null
}
},
/**
- 組件的初始數據
*/
data: {
cardInfo: []
},