wx.setStorageSync(string key, any data)
wx.setStorage 的同步版本
wx.setStorage({
key:"key",
data:"value"
})
try {
wx.setStorageSync('key', 'value')
} catch (e) { }
wx.getStorageSync(string key)
wx.getStorage 的同步版本
wx.getStorage({
key: 'key',
success (res) {
console.log(res.data)
}
})
try {
var value = wx.getStorageSync('key')
if (value) {
// Do something with return value
}
} catch (e) {
// Do something when catch error
}
wx.removeStorageSync(string key)
wx.removeStorage 的同步版本
wx.removeStorage({
key: 'key',
success (res) {
console.log(res)
}
})
try {
wx.removeStorageSync('key')
} catch (e) {
// Do something when catch error
}
wx.clearStorageSync()
wx.clearStorage 的同步版本
wx.clearStorage()
try {
wx.clearStorageSync()
} catch(e) {
// Do something when catch error
}
童话故事
早间新闻
{{val.name}}--{{i}}--{{j}}
/* pages/02storage/02storage.wxss */
page{
background-color: #eee;
}
.item{
height: 100rpx;
line-height: 100rpx;
background-color: #fff;
margin-right: 10rpx 0;
}
.title{
color: #fff;
}
.title text{
background-color: #ccc;
padding: 0 40rpx;
}
button{
vertical-align: middle;
margin: 10rpx 0;
}
// pages/02storage/02storage.js
Page({
/**
* 页面的初始数据
*/
data: {
lists: [
[
{"id":"1001","type":"1","name":"格林童话"},
{"id":"1002","type":"1","name":"儿童童话"},
{"id":"1003","type":"1","name":"寓言童话"}
],
[
{"id":"1004","type":"2","name":"早间新闻"},
{"id":"1005","type":"2","name":"午间新闻"},
{"id":"1006","type":"2","name":"晚间新闻"},
{"id":"1007","type":"2","name":"今日新闻"}
]
]
},
/*设置缓存 (key,value)
同步
wx.setStorageSync('key', data)
异步回调
wx.setStorage({
data: data,
key: 'key',
})
*/
_setStorage(e){
// 可以通过下标,或 将对象传过来
let {i,j,id,obj} = e.currentTarget.dataset;
// console.log(i,j,obj)
// i:0 story 故事 i:1news新闻
// 1 先获取对应缓存数据
//存储成数组的结构
//做一个分类: 故事(key:story) 新闻( key:news )
const key = i == 0 ? 'story' : 'news';
// 如何没有缓存 赋值默认
let datas = wx.getStorageSync(key) || [];
// 判断缓存是否有该数据
let a = datas.findIndex((val,idx)=>{
console.log(val.id===id,111)
return val.id===id
})
console.log(a)
if(a == -1){
datas.push(this.data.lists[i][j]);
// 存储到缓存
wx.setStorageSync(key, datas);
}else{
console.log('已经存在')
}
},
// 删除故事的缓存
_removeStory(){
wx.removeStorageSync('story')
},
// 删除所有
_clearAll(){
wx.clearStorageSync();
}
})