【微信小程序】缓存基础——存储、获取、移除、清理(异步)

文章目录

  • 前端页面wxml
  • js数据定义
  • *存储缓存
  • *获取缓存
  • *移除缓存
  • *清理缓存
  • wxss
  • 缓存应用场景


前端页面wxml

<button bindtap="setStorageVal3" data-num3="3" >将数值3存入缓存button>
<button bindtap="delStorage">删除指定缓存button>
<button bindtap="clearStorage">清除所有缓存button>
<button bindtap="showStorageVal3">显示当前缓存button>
<text wx:if="{{isShowText}}">{{showText}}text>

js数据定义

data: {
        isShowText:false,
        value:0,
        showText:'',
},

*存储缓存

	//将数值3存入缓存
    setStorageVal3(e){
        // 开启加密存储
        wx.setStorage({
            key: "value",
            data: e.currentTarget.dataset.num3,
            encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
            success() {
                wx.getStorage({
                    key: "key",
                    encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
                    success(res) {
                        console.log(res.data)
                    }
                })
            }
        })
    },

开发者查看缓存:

【微信小程序】缓存基础——存储、获取、移除、清理(异步)_第1张图片

*获取缓存

注:在success回调函数中,this.setData中的this对象已经不是page了,所以在success之前应该把page对象赋值给新建的对象

showStorageVal3(){
    var that = this;//把page对象赋值给新建的对象
    wx.getStorage({
        key: "value",
        encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
        success(res) {
            that.setData({
                isShowText:true,
                showText:res.data
            })
        },
        fail(res){
            // console.log(res);
            that.setData({
                isShowText:false,
            })
        }
    })
},

*移除缓存

removeStorage移除缓存指的是移除指定缓存,需要指定key值

//删除指定缓存
delStorage(){
    wx.removeStorage({
        key: 'value',
        success (res) {
            console.log(res.errMsg)
        }
    })
},

*清理缓存

clearStorage移除缓存指的是移除所有缓存,不需要指定key值(即使指定了也没用)(一键清楚所有烦恼)

//清除所有缓存
clearStorage(){
    var that = this;
    wx.clearStorage({
      success: (res) => {
          console.log(res);
          that.setData({
              isShowText:false,
          })
      },
    })
},

wxss

button{
	margin-top: 30rpx;
	border: black 1rpx solid;
	background: rgb(7,193,96);
	box-shadow: gray 8rpx 8rpx 2rpx 2rpx;
}
text{
	width: 80%;
	height: 200rpx;
	margin: 10%;
	text-align: center;
	line-height: 2em;
	background: lightblue;
	color: black;
	font-size:100rpx;

}

缓存应用场景

本地数据缓存:就是将小程序的数据存储在当前设备硬盘上。
本地数据缓存的作用:

  • 存储用户在小程序上产生的操作,在用户关闭小程序重新打开时可以恢复之前的状态。
  • 缓存一些服务端非实时的数据,从而提高小程序获取数据的速度。

你可能感兴趣的:(小程序,微信小程序,缓存)