vuex介绍

132 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1. vuex的基本介绍

vuex是vue中的状态管理工具,采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

也就是说,当有多个视图依赖于同一状态时,(比如多个页面都需要权限状态时),或者不同视图的行为需要改变同一个状态时,这样使用父传子,多层嵌套会很麻烦,这时就可以使用vuex。

2. Vuex 的5个属性,包含 state,mutations,getters,actions,modules

  1. state: 数据存储

  2. getters: 可以认为是state的计算属性,返回值会根据他的依赖缓存起来,当依赖值改变时才会被重新计算

  3. mutations: 只能通过提交mutation改变state值,mutation中必须是同步函数,通过store.commit('mutations-name')

  4. actions: 类似于mutation,action提交的是mutation,不能直接改变state;action可以写任何异步操作;

    1. actions中的函数,第一个值是对象,{commit},第二个值是需要传入的数据;
    2. actions默认返回的是Promise,store.depatch返回的也是Promise,store.depatch('actions-name')
  5. Modules: 所有的状态很多时,可以进行分割,每个模块拥有自己的 state、mutation、action、getter

3. 项目结构

1.png

4. vuex的使用及实例

例如权限问题

1.建立store文件夹,index.js中 引入使用vuex

import Vue form 'vue';
import Vuex form 'vuex';
import modules from './modules';

Vue.use(Vuex);

const state = {
    auth: {}//权限
};
const mutations = {
    // 函数第二个值payload,一般为一个对象
    changeAuth(state, data) {
        state.auth = data.elementData;
        state.admin = data.isAdmin;
    }
};
const actions = {};

export default new Vuex.Store({
    state: Object.assign({}, state),
    getters: Object.assign({}, getters),
    actions: Object.assign({}, actions),
    mutations: Object.assign({}, mutations),
    modules: modules,
    strict: process.env.NODE_ENV !== 'production',
});

使用modules,存放开关

const state = () => ({});

// getters
const getters = {};

// actions,actions中处理异步函数
const actions = {
    // 获取功能开关数据
    async actionFunctionSwitch(context) {
        const res = await window.vueInstance.$request({
            url: api.featureSwitch,
            methods: 'GET',
            showLoading: false,
        });
        // actions提交mutations
        context.commit('functionSwitch', res.data.data);
    },
};

// mutations
const mutations = {
    functionSwitch(state, data) {
        state.permision = data;
    },
};

export default {
    state,
    getters,
    actions,
    mutations,
};

2. 在main.js中引入store

import store from './store/';
new Vue({
  el: '#app',
  store
})

3. 在组件中使用

比如,需要用到state下的auth

// 直接使用$store.state
<p></p>
// 使用mapState
import { mapState } from 'vuex';
computed: {
    // 使用数组方式,映射 this.auth 为 this.$store.state.auth
    ...mapState(['auth'])
    // 使用对象方式,可以重新命名
    ...mapState({
      authName: 'auth'
    })
}

必须通过mutations修改state,异步操作使用actions修改mutations

例如,想改变auth的值

const newAuth = {...}
updateAuth() {
    this.$store.commit('auth',newAuth)
}

Action 通过 store.dispatch 方法触发:

if (productConfig.hasAuth) {
    saasv._router.beforeEach(async (to, from, next) => {
        if (initload) {
            await store.dispatch('actionFunctionSwitch');
            await store.dispatch('actionGetAuth');
            initload = false;
            next();
        } else {
            next();
        }
    });
}

可以使用mapState,mapGetters辅助函数在计算属性computed中实现;mapMutations在methods中实现