這里我寫(xiě)一個(gè)最簡(jiǎn)單的例子,方便你擴(kuò)展
存放目錄
本地存儲(chǔ)插件 localstorage.js 我放到了plugins下
組件搭建
創(chuàng)建存儲(chǔ)關(guān)鍵字
const STORE_KEY = 'STORE-KEY';
創(chuàng)建初始化函數(shù)和存儲(chǔ)方法
export default{
data:null,
install: function(Vue) {
this.data = JSON.parse(window.localStorage.getItem(STORE_KEY)) || {};
if(this.data==null){
this.data = {};
}
Vue.prototype.$local = this;
// this.clearItems();
},
save(){
window.localStorage.setItem(STORE_KEY, JSON.stringify(this.data))
},
}
啟用
/**本地存儲(chǔ) */
import local from "./plugins/localstorage"
Vue.use(local);
使用
在任意當(dāng)前模版下調(diào)用
this.$local.save()
- 其他函數(shù)可自行擴(kuò)展
- 這里將對(duì)象進(jìn)行json序列化,讀取的時(shí)候從json中還原回去
- 存儲(chǔ)方法可以在router中寫(xiě)明,在切換頁(yè)面時(shí)存儲(chǔ)