uni-app:本地缓存

有时需要将数据临时存储到本地缓存,而不是存储到数据库,

1、uni.setStorage

将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。

<template>
    <view>
        <button type="primary" @click="setStor">存储数据</button>
    </view>
</template>

<script>
    export default {
        methods: {
            setStor () {
                uni.setStorage({
                     key: 'id',
                     data: 100,
                     success () {
                         console.log('存储成功')
                     }
                 })
            }
        }
    }
</script>

<style>
</style>

存储成功之后,浏览器中查看:Application>localstorage,微信开发者工具中查看:storage

2、uni.setStorageSync

将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。推荐使用同步的接口,因为比较方便。

<template>
    <view>
        <button type="primary" @click="setStor">存储数据</button>
    </view>
</template>

<script>
    export default {
        methods: {
            setStor () {
                uni.setStorageSync('id',100)
            }
        }
    }
</script>

<style>
</style>

3、uni.getStorage

从本地缓存中异步获取指定 key 对应的内容。

<template>
    <view>
        <button type="primary" @click="getStorage">获取数据</button>
    </view>
</template>
<script>
    export default {
        data () {
            return {
                id: ''
            }
        },
        methods: {
            getStorage () {
                uni.getStorage({
                    key: 'id',
                    success:  res=>{
                        console.log("获取成功",res)
                    }
                })
            }
        }
    }
</script>

注意:res={data:key对应的内容}

4、uni.getStorageSync

从本地缓存中同步获取指定 key 对应的内容。

<template>
    <view>
        <button type="primary" @click="getStorage">获取数据</button>
    </view>
</template>
<script>
    export default {
        methods: {
            getStorage () {
                const id = uni.getStorageSync('id')
                console.log(id)
            }
        }
    }
</script>

5、uni.removeStorage

从本地缓存中异步移除指定 key。

<template>
    <view>
        <button type="primary" @click="removeStorage">删除数据</button>
    </view>
</template>
<script>
    export default {
        methods: {
            removeStorage () {
                uni.removeStorage({
                    key: 'id',
                    success: function () {
                        console.log('删除成功')
                    }
                })
            }
        }
    }
</script>

6、uni.removeStorageSync

从本地缓存中同步移除指定 key。

<template>
    <view>
        <button type="primary" @click="removeStorage">删除数据</button>
    </view>
</template>
<script>
    export default {
        methods: {
            removeStorage () {
                uni.removeStorageSync('id')
            }
        }
    }
</script>
原文地址:https://www.cnblogs.com/zwh0910/p/14537566.html