本地存储 、获取、移除、方法的封装
<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>
网友评论