1、在libs文件下先建一个tools.js(可直接复制)
//判断是否为空
export function validatenull(val) {
if (typeof val == 'boolean') {
return false;
}
if (typeof val == 'number') {
return false;
}
if (val instanceof Array) {
if (val.length == 0) return true;
} else if (val instanceof Object) {
if (JSON.stringify(val) === '{}') return true;
} else {
if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
return false;
}
return false;
}
2、在libs下建storage.js(可直接复制)
import { validatenull } from '@/libs/tools';
const keyName = '' + '-';//随便写个自己的标识
//存储sessionStorage
export const setStore = (params = {}) => {
let {
name,
content,
type,
} = params;
name = keyName + name
let obj = {
dataType: typeof (content),
content: content,
type: type,
datetime: new Date().getTime()
}
if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
else window.localStorage.setItem(name, JSON.stringify(obj));
}
//获取sessionStorage
export const getStore = (params = {}) => {
let {
name,
debug
} = params;
name = keyName + name
let obj = {},
content;
obj = window.sessionStorage.getItem(name);
if (validatenull(obj)) obj = window.localStorage.getItem(name);
if (validatenull(obj)) return;
try {
obj = JSON.parse(obj);
} catch{
return obj;
}
if (debug) {
return obj;
}
if (obj.dataType == 'string') {
content = obj.content;
} else if (obj.dataType == 'number') {
content = Number(obj.content);
} else if (obj.dataType == 'boolean') {
content = eval(obj.content);
} else if (obj.dataType == 'object') {
content = obj.content;
}
return content;
}
3、在store下新建user.js
import { setStore, getStore } from '@/libs/storage';
export default {
state: {
demo: getStore({ name: 'demo' }) || '',
//getters里的例子
todos: [
{ id: 1, text: '水果类', done: true },
{ id: 2, text: '苹果', done: true },
{ id: 3, text: '苹果', done: false}
]
},
mutations: {
//同步操作
setdemo(state, demo) {
state.demo = demo
setStore({ name: 'demo', content: state.demo, type: 'session' })
},
},
getters: {
//我们可以认为,【getters】是store的计算属性,操作state里的数据。
doneTodos: state => {//通过方法访问
return state.todos.filter(todo => todo.done)
}
},
actions: {
//暴露给用户使用,借此触发mutations中的方法,保存数据(可执行异步操作)
methodName({ state,commit },{data} ){
commit('setdemo','存储数据')
}
}
}
4、store下的index.js:引入相应模块,暴露出store,供vue注册后全局使用
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
namespaced: true, // 为了解决不同模块命名冲突的问题
user
}
})
5、main.js中引入index.js
import store from './store/index'
6、存取数据
//mutations
//存
this.$store.commit('方法名',值) //方法名是vuex中的方法名
//取
this.$store.state
//actions
//触发
this.$store.dispatch('方法名')
//使用mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用
import { mapActions } from 'vuex'
methods: {
...mapActions(['方法名','方法名'])
}
//使用
this.方法名