在src下新建utils,新建storage.js
//storage.js
let ls = window.localStorage
let ss = window.sessionStorage
export const locStorage = {
set(name, content) {
if (!name) return
ls.setItem(name, JSON.stringify(content))
},
get(name) {
try {
return JSON.parse(ls.getItem(name))
} catch (e) {
return null
}
},
remove(name) {
if (!name) return
ls.removeItem(name)
},
clear() {
ls.clear()
}
}
export const sesStorage = {
set(name, content) {
if (!name) return
ss.setItem(name, JSON.stringify(content))
},
get(name) {
try {
return JSON.parse(ss.getItem(name))
} catch (e) {
return null
}
},
remove(name) {
if (!name) return
ss.removeItem(name)
},
clear() {
ss.clear()
}
}
使用
在使用的页面引入
import { locStorage } from '@/utils/storage'
<template>
<div class="main-wrapper">
<head-top></head-top>
<button @click="locStorage()">点击存储</button>
<button @click="getStorage()">点击获取</button>
</div>
</template>
<script>
import { locStorage } from '@/utils/storage'
export default {
name: "localStorage",
methods:{
locStorage() {
let arr1 = [1,'xiaoxi','qq']
locStorage.set('list',arr1)
},
getStorage() {
let list = locStorage.get('list')
console.log(list)
}
}
}
</script>
<style scoped>
.main-wrapper {
margin-left: 20px;
}
</style>
image.png
网友评论