1 使用template模板、數據抽取
- 項目的目錄
- 代碼的邏輯流程
2 緩存
- 在上面 1 流程的基礎上,app.js中添加如下代碼,具有緩存作用
第一種
var shopData = require("./demo2/templates/data.js")
App({
onLaunch: function() {
// 緩存
wx.setStorage({
key: 'newshopList',
data: shopData.shop,
success: function(res) {},
fail: function() {},
complete: function() {}
})
}
})
第二種同步緩存
var shopData = require("./demo2/templates/data.js")
App({
onLaunch: function() {
// 同步設置緩存
var loadShop = wx.getStorageSync('newshopList');
if(!loadShop){
//如果緩存不存在
var dataShop = require("./demo2/templates/data.js")
wx.clearStorageSync();
wx.setStorageSync('newshopList', dataShop.shop);
}
}
})
3 使用緩存操作類
註釋掉 2 中的代碼
- 在 上面 1流程基礎上,templates文件夾中添加cacheShop.js
class CacheShop {
constructor() {
this.shopKey = 'shopListKey' // 自定義本地緩存鍵值
}
// 獲取數據
GetAllShopData() {
let res = wx.getStorageSync(this.shopKey)
if (!res) {
res = require('./data.js').shop // 獲取數據
this.SaveShopData(res)
}
return res
}
//保存或更新緩存數據
SaveShopData(data) {
wx.setStorageSync(this.shopKey, data)
}
}
export {
CacheShop
}
- 更改demo2.js
import { CacheShop } from './templates/cacheShop.js'
Page({
data: {},
onLoad: function () {
let shops = new CacheShop()
this.setData({
newshopList: shops.GetAllShopData()
})
}
})
- 查看緩存效果
爲保證代碼緩存的正確性,改變代碼,點擊清除數據緩存
沒有直接上代碼,下面也是部分代碼(沒有添加樣式抽取) ,可能會看的雲裏霧裏;
如若裏面的圖片無法保證明白template的 邏輯流程 ,最下面是全部代碼壓縮包的鏈接
鏈接:https://pan.baidu.com/s/1TWXVc05nMA723O1hBOzOlQ
提取碼:tzcf