stroageState Vue 缓存hook
2020-04-07 本文已影响0人
copyLeft
chart.gif
使用例子
<template>
<div class="home">
<div>
<Card style='margin: 20% auto; width: 600px' title=''>
<p> {{ userInfo }} </p>
<Input v-model="userName" />
<Button @click='updateUserName' > update </Button>
<Button @click='clearUserInfo' > clear </Button>
<Button @click='addPrefix' > addPrefix </Button>
</Card>
</div>
</div>
</template>
<script>
import { ref } from '@vue/composition-api'
import strongeStateHook from '@/hooks/strongeStateHook'
export default {
setup(){
const [ userInfo, updateState ] = strongeStateHook(localStorage, 'USER_INFO', { name: 'coco' })
const userName = ref('')
const updateUserName = () => updateState({ ...userInfo.value, name: userName.value })
const clearUserInfo = () => updateState()
const addPrefix = () => updateState(userInfo => { return { name: `super-${userInfo.name}` } })
return {
userName,
userInfo,
updateUserName,
clearUserInfo,
addPrefix
}
}
}
</script>
实现
import { ref } from '@vue/composition-api'
function isFunction(obj){
return typeof obj === 'function'
}
function getStoreValue(storage, key, defaultValue){
const raw = storage.getItem(key)
if(raw){
return JSON.parse(raw)
}
if(isFunction(storage)){
return defaultValue()
}
return defaultValue
}
/**
*
* @param { localStorage | sessionStorage } storage
* @param { string } key 缓存字段名
* @param { any } defaultValue 默认数据
* @returns { array } [ state, updateState ] 返回缓存ref对象,及更新方法。 更新数据为空时,清楚缓存字段
* @summary 缓存基础函数,封装解析及格式化操作
* @example
*
* const [ userInfo, updateState ] = strongeStateHook(localStorage, 'USER_INFO', { nickname: 'coco', age: 24 })
*
* const closeUserInfo = () => updateState()
* const updateNickname = name => updateState({ ...userInfo.value, nickname: name })
*
*/
export default function stroageState(storage, key, defaultValue){
const state = ref( getStoreValue(storage, key, defaultValue) )
function updateState(value){
if(typeof value === 'undefined'){
storage.removeItem(key)
state.value = undefined
return
}
if(isFunction(value)){
const previousState = getStoreValue(storage, key, defaultValue)
const currentState = value(previousState)
storage.setItem(key, JSON.stringify(currentState))
state.value = currentState
return
}
storage.setItem(key, JSON.stringify(value))
state.value = value
}
return [ state, updateState ]
}