数据缓存
有的时候我们的数据临时存储到本地而不是存储到咱们后台的数据库
这里可以用到本地的数据缓存
就可以了
主要是三个方法
uni.setStorage(设置缓存)
没有带Sync
是值这个方法是异步接口
设置这个数据就可以调用我们uni.setStorage
方法这个方法需要传入一个配置对象:
uni.setStorage(OBJECT):
OBJECT 参数说明
参数名 | 类型 | 必填 | 说明 |
key | String | 是 | 本地缓存中的指定的 key |
data | Any | 是 | 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象 |
success | Function | 否 | 接口调用成功的回调函数 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
测试:
<template>
<div>
<button type="primary" @click="setStor">存储数据</button>
</div>
</template>
<script>
export default{
name:'Stor',
components:{},
data() {
return {
}
},
methods: {
setStor(){
uni.setStorage({
key: 'id',
data: 80,
success(){
console.log('存储成功')
}
})
}
},
}
</script>
<style scoped>
</style>
h5在Application
里面,微信小程序在Storage
里面
uni.setStorageSync
带Sync
是指我们这个方法同步的这个版本
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
参数说明
参数 | 类型 | 必填 | 说明 |
key | String | 是 | 本地缓存中的指定的 key |
data | Any | 是 | 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象 |
uni.setStorageSync('id',100)
uni.getStorage(获取缓存)
从本地缓存中异步获取指定 key 对应的内容。
uni.setStorage(OBJECT):
OBJECT 参数说明
参数名 | 类型 | 必填 | 说明 |
key | String | 是 | 本地缓存中的指定的 key |
success | Function | 是 | 接口调用的回调函数,res = {data: key对应的内容} |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
验证:
<template>
<div>
<button type="primary" @click="getStor">获取数据</button>
</div>
</template>
<script>
export default{
name:'Stor',
components:{},
data() {
return {
}
},
methods: {
getStor(){
uni.getStorage({
key:'id',
success(res){
//console.log('获取成功',res)
console.log('获取成功',res.data)
}
})
}
},
}
</script>
<style scoped>
</style>
uni.getStorageSync(KEY)
从本地缓存中同步获取指定 key 对应的内容。
参数说明
参数 | 类型 | 必填 | 说明 |
key | String | 是 | 本地缓存中的指定的 key |
getStor(){
const key = uni.getStorageSync('id')
if(key){
console.log('获取到值了',key)
}
}
uni.removeStorage(移除)
从本地缓存中异步移除指定 key。
OBJECT 参数说明
参数名 | 类型 | 必填 | 说明 |
key | String | 是 | 本地缓存中的指定的 key |
success | Function | 是 | 接口调用的回调函数 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
测试:
<template>
<div>
<button type="primary" @click="setStor">存储数据</button>
<button type="primary" @click="getStor">获取数据</button>
<button type="primary" @click="removeStor">删除id</button>
</div>
</template>
<script>
export default{
name:'Stor',
components:{},
data() {
return {
}
},
methods: {
setStor(){
uni.setStorage({
key: 'id',
data: 80,
success(){
console.log('存储成功')
}
})
},
getStor(){
uni.getStorage({
key:'id',
success(res){
console.log('获取成功',res)
},
fail(){
console.log('获取失败')
}
})
},
removeStor(){
uni.removeStorage({
key: 'id',
success(){
console.log('删除成功')
}
})
}
},
}
</script>
<style scoped>
</style>
uni.removeStorageSync(KEY)
从本地缓存中同步移除指定 key。
参数说明
参数名 | 类型 | 必填 | 说明 |
key | String | 是 | 本地缓存中的指定的 key |
uni.removeStorageSync('id')
其他可以参考官方文档