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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM