封装storage
const STORAGE_KEY = 'aqd'
export interface storageInstance {
getStorage(): any
clearModuleKye(key:string,module_name:string):any
clearKey(key:string):any
getItemModule(key:string,module_name:string):any
getItemKey(key:string):any
setItemMOduleKey(key:string,value:any,module_name:string):void
setItemKey(key:string,value:any):void
}
class storageClass implements storageInstance{
getStorage() {
return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}')
}
clearModuleKye(key:string,module_name:string) {
const val = this.getStorage()
if (!val[module_name]) return
delete val[module_name][key]
return window.localStorage.setItem(STORAGE_KEY,JSON.stringify(val))
}
clearKey(key:string) {
const val = this.getStorage()
delete val[key]
return window.localStorage.setItem(STORAGE_KEY,JSON.stringify(val))
}
getItemModule(key:string,module_name:string) {
const val = this.getItemKey(module_name)
if (val) return val[key]
return this.getStorage()[key]
}
getItemKey(key:string) {
return this.getStorage()[key]
}
setItemMOduleKey(key:string,value:any,module_name:string) {
const val = this.getStorage()
val[key] = value
this.setItemKey(module_name,val)
}
setItemKey(key:string,value:any) {
const val = this.getStorage()
val[key] = value
window.localStorage.setItem(STORAGE_KEY,JSON.stringify(val))
}
}
const storage = new storageClass()
export default storage
创建storage.d.ts
import { ComponentCustomProperties } from 'vue'
import storageClass,{storageInstance} from "@/storage";
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$storage: storageClass<storageInstance>
}
}
就可以直接调用
import { createStore } from 'vuex'
export default createStore({
state: {
username: ''
},
mutations: {
saveUserName(state,username) {
state.username = username
}
},
actions: {
saveUserName(content,username) {
content.commit('saveUserName',username)
}
},
modules: {
}
})
去登录页面调用
this.$store.dispatch('saveUserName',data)
export default class App extends Vue {
mounted() {
const a = this.$storage.getItemKey('userinfo')
this.$store.dispatch('saveUserName',a)
console.log(a,"dfdf")
}
}
当然应该是网络请求回去用户信息的,如果登录过就返回用户信息,如果没有登录就返回制定状态码,跳转到登录页面,这个是放在刷新后信息丢失