state.js :
const state = {
name:"123",
age:456
};
export default state
store.js: 在main.vue中加入
import Vue from 'vue'
import Vuex from 'vuex'
import STATE from './state.js'
Vue.use(Vuex);
const store = new Vuex.Store({
state: STATE,
mutations: {
set (state, keysVal) {
let tmp = state
let keysTemp = keysVal.keys.split('.')
let keys = []
if (keysTemp.length > 2) {
for (let i = 0; i < keysTemp.length; i++) {
if (i > 1) {
keys[1] = keys[1] + '.' + keysTemp[i]
} else {
keys[i] = keysTemp[i]
}
}
} else {
keys = keysTemp
}
keys.map((key, idx) => {
if (idx === keys.length - 1 || idx === 1) {
tmp[key] = keysVal.val
} else {
tmp[key] = {}
tmp = tmp[key]
}
})
},
clean (state) {
for (let key in INIT_STATE) {
state[key] = INIT_STATE[key]
}
}
}
})
export default store
index.js : 需要使用状态时引入
import store from './store'
const env = process.env.NODE_ENV
function _store (keys, val) {
if (typeof val === 'undefined') {
let keysTemp = keys.split('.')
keys = []
if (keysTemp.length > 2) {
for (let i = 0; i < keysTemp.length; i++) {
if (i > 1) {
keys[1] = keys[1] + '.' + keysTemp[i]
} else {
keys[i] = keysTemp[i]
}
}
} else {
keys = keysTemp
}
return keys.reduce((v, k) => {
if (v && v.hasOwnProperty(k)) {
return v[k]
} else {
return null
}
}, store.state)
} else {
store.commit('set', {
keys,
val
})
}
}
function _storage (key, val) {
let ciKey = 'vue_storage_' + env
let envData = _lstorage(ciKey)
if (typeof val === 'undefined') {
if (envData && envData[ciKey] && envData[ciKey][key]) {
return envData[ciKey][key]
} else {
return null
}
} else {
if (_storage(key)) {
envData[ciKey][key] = val
_lstorage(ciKey, envData)
}
if (!envData || typeof envData !== 'object') {
envData = {}
}
if (!envData[ciKey]) {
envData[ciKey] = {}
}
envData[ciKey][key] = val
_lstorage(ciKey, envData)
}
}
function _lstorage (key, val) {
if (typeof val === 'undefined') {
try {
return JSON.parse(localStorage.getItem(key))
} catch (e) {
return null
}
} else {
localStorage.setItem(key, JSON.stringify(val))
}
}
function _ustorage (key, val) {
let userData = _storage('user_data')
const user = _storage('user')
let uid = user ? user.user_id : null
if (!uid) {
return null
}
if (typeof val === 'undefined') {
if (userData && userData[uid] && userData[uid][key]) {
return userData[uid][key]
} else {
return null
}
} else {
if (_ustorage(key)) {
userData[uid][key] = val
_storage('user_data', userData)
}
if (!userData || typeof userData !== 'object') {
userData = {}
}
if (!userData[uid]) {
userData[uid] = {}
}
userData[uid][key] = val
_storage('user_data', userData)
}
}
function cleanUstorage () {
_storage('user_data', {})
}
function cleanStore () {
store.commit('clean')
}
export default {
store: _store,
ustorage: _ustorage,
storage: _storage,
cleanUstorage,
cleanStore
}
使用方式
import store from '***/index.js'
store.store(key); //获取数据
store.store(key,value) // 保存数据
store.storage(key) // 从localstorage 获取数据
store.storage(key,value) //保存数据到localStorage