美文网首页
2020-11-04

2020-11-04

作者: Luoyilin | 来源:发表于2020-11-04 16:23 被阅读0次
本地存储 、获取、移除、方法的封装
<template>
    <div>
     <button @click="setStorage">本地数据存储</button>
     <button @click="removeStorage">清除本地数据</button>
    </div>
</template>
<script>
export default {
    data(){
        return{
           num:[]
        }
    },
    mounted() {
         this.getLocalStorage({/**获取本地存储的数据 */
             key:'localText',
             success:(data)=>{
                 this.num = data ==null ? []:data
             }
         })
    },
    methods: {
        removeStorage(){/**清除本地数据*/
             this.removeLocalStorage({
                key:'localText',
                success:()=>{
                    this.num=[]
                }
            })
        },
        setStorage(){/**本地存储公用方法的调用 */
                let nums = Math.ceil(Math.random()*10).toString() /**0-9随机数的获取 */
                this.num.unshift(nums)
                this.setLocalStorage({
                    key:'localText',
                    data:this.num
                })

        },
        setLocalStorage({key,data}){
            window.localStorage.setItem('key',JSON.stringify(data))
        },
        getLocalStorage({key,success}){
            let data = window.localStorage.getItem('key');
            success(JSON.parse(data))
        },
        removeLocalStorage({key,success}){
            window.localStorage.removeItem('key')
            success()
        }
    },
}
</script>



相关文章

网友评论

      本文标题:2020-11-04

      本文链接:https://www.haomeiwen.com/subject/ieygvktx.html