本地存儲 、獲取、移除毕荐、方法的封裝
<template>
<div>
<button @click="setStorage">本地?cái)?shù)據(jù)存儲</button>
<button @click="removeStorage">清除本地?cái)?shù)據(jù)</button>
</div>
</template>
<script>
export default {
data(){
return{
num:[]
}
},
mounted() {
this.getLocalStorage({/**獲取本地存儲的數(shù)據(jù) */
key:'localText',
success:(data)=>{
this.num = data ==null ? []:data
}
})
},
methods: {
removeStorage(){/**清除本地?cái)?shù)據(jù)*/
this.removeLocalStorage({
key:'localText',
success:()=>{
this.num=[]
}
})
},
setStorage(){/**本地存儲公用方法的調(diào)用 */
let nums = Math.ceil(Math.random()*10).toString() /**0-9隨機(jī)數(shù)的獲取 */
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>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者