uniapp封装本地存储处理数据的方法和注意使用

js文件

//存储数据
function setStoraged(data1, data2) {
    uni.setStorage({
        key: data1,
        data: JSON.stringify(data2),
    })
}
//获取数据
function getStoraged(data1) {
    const data = uni.getStorageSync(data1);
    if (data) {
        return data;
    } else {
        return [];
    }

}
//删除数据
function removeStoraged(data1) {
    uni.removeStorageSync(data1);
}
export {
    setStoraged,
    getStoraged,
    removeStoraged
}

页面应用

导入

import {
        setStoraged,
        getStoraged,
        removeStoraged
    } from '../../unils/storageData.js'

使用

 setStoraged('value', '123');
  let datas = getStoraged('colData');
  if (datas[0]) {
     datasArr = JSON.parse(getStoraged('colData'));
   }
   removeStoraged('value');         

注意使用!!!!!===================================

成功获取数据但未使用箭头函数,都能打印出来,但是未箭头函数时候data数据v-bind不能获取到:(失败例子):

info() {
				//异步存储
					uni.setStorage({
						key:'id',
						data:{
							host: "127.0.0.1",
							key: "21313123213"
						},
						success() {
							console.log('存储成功!')
						}
					})
			},
			into(){
				uni.getStorage({
					//读取数据
						key:'id',
						success(res){
							// console.log(res);
							// this.username=res.data;
							// console.log(this.username.host);
							var _that = this;
							
							_that.host = res.data.host;
							_that.key = res.data.key;
							console.log(_that.host);
							console.log(_that.key);
						}
									
					})
			},

成功读取数据使用箭头函数,都能打印出来,但是使用箭头函数时候data数据v-bind才能获取到: (成功例子):

info() {
				//异步存储
					uni.setStorage({
						key:'id',
						data:{
							host: "127.0.0.1",
							key: "21313123213"
						},
						success:()=> {
							console.log('存储成功!')
						}
					})
			},
			into(){
				uni.getStorage({
					//读取数据
						key:'id',
						success: (res)=>{
							// console.log(res);
							// this.username=res.data;
							// console.log(this.username.host);
							var _that = this;
							//this.host和this.key是data里数据
							_that.host = res.data.host;
							_that.key = res.data.key;
							console.log(_that.host);
							console.log(_that.key);
//都能打印出来,但是使用箭头函数时候data数据v-bind才能获取到
						}
									
					})
			},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值