创建store目录及其文件:
store文件夹下的index.js代码:
import user from './modules/user.js'
import test from './modules/test.js'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user,
test,
},
})
export default store
user.js中的代码:
export default {
namespaced: true,
state: {
token: localStorage.token,
tokenExpired: localStorage.tokenExpired,
userInfo: {},
},
getters: {
isTokenValid(state) {
return !!state.token && state.tokenExpired > Date.now()
},
},
mutations: {
// 如果有两个以上的参数,应当将其作为一个对象来传参
SET_TOKEN: (state, { token, tokenExpired }) => {
state.token = token
state.tokenExpired = tokenExpired
localStorage.token = token
localStorage.tokenExpired = tokenExpired
},
REMOVE_TOKEN: (state) => {
state.token = ''
state.tokenExpired = 0
state.userInfo = {}
localStorage.clear()
},
SET_USER_INFO: (state, userInfo) => {
state.userInfo = userInfo
},
},
actions: {},
}
调用的方法:
<template>
<div>
{{ tokenExpired }}{{ isvalid }}
</div>
</template>
<script>
import { mapState, mapGetters ,mapMutations } from 'vuex'
export default {
computed: {
...mapState('test', ['count']),
...mapState('user', ['tokenExpired', 'token']),
...mapGetters({
isvalid: 'user/isTokenValid',
}),
},
methods: {
...mapMutations({
saveToken(commit,obj){
commit('user/SET_TOKEN',obj)
}
}),
test() {
this.saveToken({
token: this.token,
tokenExpired:this.tokenExpired
})
},
},
}
</script>
以上是vuex使用的一个简单示例。