一、简介
将数据设置成缓存:uni.setStorageSync(想要存储的名字, 需存储的数据);
获取本地数据缓存:uni.getStorageSync(缓存的名字);
参考网址:https://uniapp.dcloud.io/api/storage/storage.html#setstoragesync
参考网址:https://uniapp.dcloud.io/api/storage/storage.html#getstorageinfo
二、案例演示
1.设置缓存
<template>
<view>
<view @click="setStorage()">点击将名字存入缓存</view>
</view>
</template>
<script>
export default {
data() {
return {
name:'张起灵',
storageName:''
};
},
onLoad() {
},
methods:{
setStorage(){
uni.setStorageSync('myName', this.name);//将名字存入缓存
}
}
}
</script>
<style lang="scss">
</style>
2.获取缓存
<template>
<view>
<view @click="setStorage()">点击将名字存入缓存</view>
</view>
</template>
<script>
export default {
data() {
return {
name:'张起灵',
storageName:''
};
},
onLoad() {
// 获取缓存
this.storageName = uni.getStorageSync('myName');
console.log(this.storageName);//打印一下查看
},
methods:{
setStorage(){
uni.setStorageSync('myName', this.name);//将名字存入缓存
}
}
}
</script>
<style lang="scss">
</style>
3.控制台查看缓存
但凡出现就说明你设置缓存成功了。
4.检测是否存在某缓存
在uni-app中,可以使用uni.getStorageInfo()方法来判断缓存是否存在。该方法会返回一个对象,其中包含了当前storage的相关信息,包括缓存的大小和已使用的空间等。可以通过判断该对象的keys属性是否包含我们想要判断的缓存键名来确定缓存是否存在。
uni.getStorageInfo({
success: function(res) {
// 判断缓存是否存在
if (res.keys.includes('yourCacheKey')) {
console.log('缓存存在');
} else {
console.log('缓存不存在');
}
}
});
请将yourCacheKey替换为你想要判断的缓存键名。
5.删除缓存
uni.removeStorageSync('type') //删除缓存
四、其他数据类型存储