什么是localStorage
在HTML5中,新加入了一個localStorage特性柠傍,這個特性主要是用來作為本地存儲來使用的,解決了cookie存儲空間不足的問題(cookie中每條cookie的存儲空間為4k)拂募,localStorage中一般瀏覽器支持的是5M大小酪捡,這個在不同的瀏覽器中l(wèi)ocalStorage會有所不同痪署。
localStorage的優(yōu)勢
1、localStorage拓展了cookie的4K限制
2谁榜、localStorage會可以將第一次請求的數(shù)據(jù)直接存儲到本地幅聘,這個相當(dāng)于一個5M大小的針對于前端頁面的數(shù)據(jù)庫,相比于cookie可以節(jié)約帶寬窃植,但是這個卻是只有在高版本的瀏覽器中才支持的
3帝蒿、localStorage與sessionStorage的唯一一點區(qū)別就是localStorage屬于永久性存儲,而sessionStorage屬于當(dāng)會話結(jié)束的時候撕瞧,sessionStorage中的鍵值對會被清空
localStorage的使用
localStorage.getItem(key):獲取指定key本地存儲的值
localStorage.setItem(key,value):將value存儲到key字段
在實際開發(fā)中陵叽,當(dāng)我們退出系統(tǒng)的時候要清除系統(tǒng)中所有的緩存
<el-menu-item index="5-3" @click="exit">退出系統(tǒng)</el-menu-item>
// 退出系統(tǒng)
exit(){
// 清除所有的緩存
localStorage.clear()
sessionStorage.clear()
this.$router.push('/')
}
切換主題 安裝Element Plus組件庫
安裝
npm install element-plus --save
在main.js中導(dǎo)入
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)
在開發(fā)當(dāng)中會有一個切換主題的應(yīng)用,怎么做呢丛版?
首先在store文件夾中新建一個module文件夾巩掺,在建一個theme.js文件
namespaced:true是為了解決不同模塊命名沖突的問題
export default {
// 為了解決不同模塊命名沖突的問題,將不同模塊的namespaced:true
namespaced:true,
state: {
// 當(dāng)前使用的主題索引
themeActive:0,
// 主題數(shù)據(jù)
themes:[
{
name:'藍(lán)色主題',
value:'#101f30'
},
{
name:'紅色主題',
value:'#f0c9cf'
},
{
name:'黃色主題',
value:'#bacf65'
},
{
name:'綠色主題',
value:'#9abeaf'
},
{
name:'紫色主題',
value:'#74759b'
}
]
},
mutations: {
updateThemeActive(state,val){
state.themeActive = val
}
},
actions: {
updateThemeActive(store,val){
store.commit('updateThemeActive',val)
}
},
}
標(biāo)簽里面的樣式
<div class="left" :style="{background:sun}"></div>
在導(dǎo)航欄里面的菜單引入
:background-color="sun"
切換主題的方法
methods: {
changeTheme(index){
// 獲取/切換 對應(yīng)的主題 theme是模塊
// 更新主題索引
this.$store.dispatch('theme/updateThemeActive',index)
// 將主題索引在瀏覽器中保存一份
localStorage.setItem('themeActive',index)
// let theme = this.$store.state.theme.themes[index]
},
},
mounted() {
let index = localStorage.getItem('themeActive')
if(index){
// 更新主題索引
this.$store.dispatch('theme/updateThemeActive',index)
}
},
computed:{
// 返回所有的主題信息
themes(){
return this.$store.state.theme.themes
},
// 返回當(dāng)前主題顏色
sun(){
return this.$store.state.theme.themes[this.$store.state.theme.themeActive].value
},
},