前端开发那些事儿

vue2.0和3.0不同的封装本地存储的写法

2020-11-23  本文已影响0人  焚心123
    <p></p>
    <button @click="set_storage"><mark>点击存储数据</mark></button>
    <p></p>
    <button @click="get_storage"><mark>点击获取存储数据</mark></button><span>{{storage_message}}</span>
    <p></p>
    <button @click="remove_storage"><mark>点击删除存储数据</mark></button>
   data(){
        return{
            storage_message:[]
        }
    },
    methods:{
        set_storage(){
            this.setStorage({//调用
                key:'storage',
                data:['1','2','3','4']
            })
        },
         get_storage(){
            this.getStorage({//调用
                key:'storage',
                success:res=>{
                    this.storage_message = res;
                }
            })
        },
         remove_storage(){
            this.removeStorage({//调用
                key:'storage',
                success:()=>{
                    this.storage_message = '我被删完啦!'
                }
            })
        },
        //设置本地存储
        setStorage({ key, data}){
            localStorage.setItem(key,JSON.stringify(data));
        },
        //获取本地存储
        getStorage({ key, success }){
            var data = localStorage.getItem(key);
            success( JSON.parse(data) );
        },
        //删除本地存储
        removeStorage({ key, success }){
            localStorage.removeItem(key);
            success();
        }
    }
setup(){
          //声明变量
        const state = reactive({
            storage_message:[]
        })
        //当前的设置本地存储的方法,要return出去,否则页面的点击事件不触发
        const set_storage = ()=>{
            setStorage({
                key:'storage',
                data:['1','2','3','4']
            })
        }
         const get_storage=()=>{
            getStorage({
                key:'storage',
                success:res=>{
                    //在vue3.0中没有this的概念,reactive变量要这样写,ref的变量要加.value
                    state.storage_message = res;
                }
            })
        }
         const remove_storage=()=>{
            removeStorage({
                key:'storage',
                success:()=>{
                    state.storage_message = '我被删完啦!'
                }
            })
        }
        //这是在js中封装的方法,可以不用return出去
        const setStorage=({ key, data})=>{
            localStorage.setItem(key,JSON.stringify(data));
        }
        const getStorage= ({ key, success }) => {
            var data = localStorage.getItem(key);
            success( JSON.parse(data) );
        }
        const removeStorage = ({ key, success }) => {
            localStorage.removeItem(key);
            success();
        }
        return {
            ...toRefs(state),//变成响应式的
            set_storage,//将template中的方法return出去
            get_storage,
            remove_storage
        }
}

上一篇下一篇

猜你喜欢

热点阅读