Vuex实现用户登陆信息数据的存储和共享

3,073 阅读1分钟

store中index.js

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
Vue.use(Vuex);

const state = {
  username:''
}
export default new Vuex.Store({
  state,
  mutations,
  actions
});

定义参数和状态

login.vue

...
methods:{
    login():{
        this.axios.post(
        ...
        ).then((res)=>{
            this.$store.dispatch('saveUserName',res.username);
        })
    }
}
...

通过dispatch触发一个action行为

action.js

export default {
  saveUserName(context, username) {
    context.commit('saveUserName', username);
  }
}

通过commit触发一个mutation,同时把参数传递进去

mutation.js

export default {
  saveUserName(state, username) {
    state.username = username;
  }
}

对状态进行赋值

nav.js

...
computed: {
    username() {
        return this.$store.state.username;
    }
}
...

渲染

如果把数据的放在data中,因为会优先加载`App.vue`组件,然后加载`nav.js`,`nav.js`中的data是同步渲染,而`App.vue`中会先请求接口来异步获取用户数据,这样就会造成data渲染为空。所以要用computed计算属性来解决这个延时问题,当渲染的时候为空,之后又获取到接口数据时,会重新调用一次computed。

App.vue

...
methods: {
    getUser() {
    this.axios.get('/user').then((res = {}) => { //未登陆状态res拉取不到可能会报错,所以赋空
        this.$store.dispatch('saveUserName', res.username);
    })
    }
}
...

之前在login.vue中获取的接口数据还没存,防止页面刷新后数据丢失,再去App.vue存取一次




当然我们可以用mapActions辅助函数(当方法、变量太多时)将组件的methods映射为stroe.dispatch调用。

login.vue

import { mapActions } from 'vuex';
...
methods:{
    login():{
        this.axios.post(
        ...
        ).then((res)=>{
    //        this.$store.dispatch('saveUserName',res.username);
        this.saveUserName(res.username);//保存用户名称到cookie里
        })
    }
    ...mapActions(['saveUserName'])
}
...

nav.js

import { mapState } from 'vuex';
...
computed: {
    ...mapState(['username'])
}
...