让数据存储到 store 中

61 阅读1分钟

首先在 store/ common.js 中 存储 要 储存的变量

在state 中定义 -- 比如 添加个变量为logId

const type = {
    SETLOGID:'SETLOGID',//设置logId
**};**
const state = {
    logId:'',//设置logId
};
const getters = {
    [type.SETLOGID](state){
        return state.logId;
    },
};

action 是 js 中可自动修改 state 的值

const actions = {  比如 === 
    login({ commit }, params) {
        return new Promise((resolve, reject) => {
            if (params) {
                commonApi.login(params).then(
                    (res) => {
                        //存储登录信息到vuex
                        commit(type.SETUSERINFO, res);
                        setUserInfo(res);
                        setToken(res.token);
                        resolve(res);
                    },
                    (err) => {
                        reject(err);
                        console.log('登录失败');
                    }
                );
            } else {
                reject();
            }
        });
    },
  }

并设置mutation

const mutations = {
    /**
     * 设置用户信息
     * @param {*} state
     * @param {*} data
     */
    [type.SETLOGID](state,data){
        state.logId = data;
    },
    [type.RESET_STATE]: (state) => {
        state.logId = ''; //logId
    },
};

最后导出

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};

在页面上如何修改 store 里面的值

引入 
import { mapMutations } from 'vuex';
调用
methods: {
    ...mapMutations ('common', ['SETLOGID']),
}

最后修改 store 的值

this.$store.commit('common/SETLOGID', res.logId);

单纯获取store的值

this.$store.state.common.logId  // 获取拿到的值