store设置如下:
主要文件是modules中的文件,以及index.js文件。
其中:index.js文件代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'
Vue.use(Vuex)
const store = new Vuex.Store({modules})
export default store
modules中index.js代码如下
import account from './account'
import setting from './setting'
import config from './config'
export default {account, setting , config}
modules中account.js代码如下
import {login, logout, getPerssions} from '@/api/account'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
namespaced: true,
state: {
user: undefined,
permissions: null,
roles: null,
routesConfig: null,
token:null
},
getters: {
user: state => {
if (!state.user) {
try {
const user = localStorage.getItem(process.env.VUE_APP_USER_KEY)
state.user = JSON.parse(user)
} catch (e) {
console.error(e)
}
}
return state.user
},
permissions: state => {
if (!state.permissions) {
try {
const permissions = localStorage.getItem(process.env.VUE_APP_PERMISSIONS_KEY)
state.permissions = JSON.parse(permissions)
state.permissions = state.permissions ? state.permissions : []
} catch (e) {
console.error(e.message)
}
}
return state.permissions
},
...
},
mutations: {
setUser (state, user) {
state.user = user
localStorage.setItem(process.env.VUE_APP_USER_KEY, JSON.stringify(user))
},
setPermissions(state, permissions) {
state.permissions = permissions
localStorage.setItem(process.env.VUE_APP_PERMISSIONS_KEY, JSON.stringify(permissions))
},
},
actions:{
// 登录
Login ({ commit }, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo).then(response => {
const {data,msg,status} = response
if(status==0){
var user={name : (data.realname ? data.realname:data.username)}
commit('setUser',user)
getPerssions().then(permissionData=>{
if(permissionData && permissionData.data && permissionData.status ==0){
commit('setPermissions',permissionData.data)
}
})
resolve(response)
}else{
reject(new Error(response))
}
}).catch(error => {
reject(error)
})
})
},
...
}
}
同样在main.js中引用和挂载
import store from './store'
new Vue({
router,
store,
...
render: h => h(App),
}).$mount('#app')
在使用的时候注意:
import {mapActions} from 'vuex'
import { mapGetters } from 'vuex'
export default {
data() {
return {
name:this.$store.state.account.user.name
};
},
computed: {
...mapGetters('account',['user']),
}
methods: {
...mapActions('account',['Login']),
toLogin(){
...
this.Login(postdata).then(res=>{
...
}).catch(error=>{
...
})
}
...
}
使用时,可以像如上代码:
this.$store.state.account.user.name
也可以使用结算数据中的值user
<input v-model="user.name"/>