前端Vue日常工作中--Vuex

前端Vue日常工作中–Vuex

Vuex提供了一个集中式的状态存储,让你可以更容易地跟踪和管理应用的状态。

1.基本使用

以下是使用Vuex的一般步骤:

  1. 安装Vuex: 在Vue.js项目中,你需要先安装Vuex。可以使用npm或者yarn:

    npm install vuex
    # 或者
    yarn add vuex
    
  2. 创建Vuex Store: 在项目中创建一个store文件夹,然后创建一个index.js文件,这将是你的Vuex存储的入口。在这个文件中,引入Vue和Vuex,然后创建一个新的Store实例:

    // store/index.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        // 状态
      },
      mutations: {
        // 更改状态的方法
      },
      actions: {
        // 触发mutations的方法,可以包含异步操作
      },
      getters: {
        // 获取状态的方法
      },
    });
    
  3. 在Vue组件中使用Vuex:

    3.1使用辅助函数

    在组件中,可以使用mapStatemapMutationsmapActionsmapGetters等辅助函数来简化对状态、mutations、actions和getters的访问。

    // 在组件中引入Vuex
    import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
    
    export default {
      computed: {
        // 使用mapState辅助函数将Vuex的state映射到组件的计算属性中
        ...mapState(['myState']),
        
        // 使用mapGetters辅助函数将Vuex的getters映射到组件的计算属性中
        ...mapGetters(['myGetter']),
      },
      methods: {
        // 使用mapMutations辅助函数将Vuex的mutations映射到组件的方法中
        ...mapMutations(['myMutation']),
        
        // 使用mapActions辅助函数将Vuex的actions映射到组件的方法中
        ...mapActions(['myAction']),
      },
    };
    

    3.2不使用辅助函数

    在组件中,可以通过 this.$store 访问 Vuex store,并直接使用其中的状态、mutations、actions 和 getters。

    export default {
      computed: {
        // 直接访问 Vuex 的 state
        myState() {
          return this.$store.state.myState;
        },
        
        // 直接访问 Vuex 的 getters
        myGetter() {
          return this.$store.getters.myGetter;
        },
      },
      methods: {
        // 直接提交 Vuex 的 mutations
        myMutation() {
          this.$store.commit('myMutation');
        },
        
        // 直接调用 Vuex 的 actions
        myAction() {
          this.$store.dispatch('myAction');
        },
      },
    };
    
    
  4. 在组件中使用状态、提交mutations、调用actions和获取getters: 你可以在组件中通过计算属性访问状态,调用mutations提交状态变更,调用actions执行异步操作,以及通过getters获取状态的派生值。

    // 访问状态
    this.yourState;
    
    // 提交mutations
    this.yourMutation();
    
    // 调用actions
    this.yourAction();
    
    // 获取getters
    this.yourGetter;
    

2.子模块使用

在Vuex中,有时你可能需要将你的状态(state)、mutations、actions和getters进行分组或模块化,以便更好地组织你的代码。这就是Vuex模块的用途。模块可以帮助你将大型的store拆分成更小、更易管理的部分。

以下是如何在Vuex中创建和使用模块的一般步骤:

  1. 创建模块: 在你的store文件夹中,创建一个包含你模块代码的文件。例如,你可以在store文件夹下创建一个名为modules的文件夹,然后在其中创建一个模块文件,比如myModule.js

    // store/modules/myModule.js
    const state = {
      // 模块的状态
    };
    
    const mutations = {
      // 模块的mutations
    };
    
    const actions = {
      // 模块的actions
    };
    
    const getters = {
      // 模块的getters
    };
    
    export default {
      namespaced: true, // 命名空间,防止命名冲突
      state,
      mutations,
      actions,
      getters,
    };
    
  2. 引入并注册模块: 在你的store/index.js中引入并注册模块。

    // store/index.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    import myModule from './modules/myModule';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      modules: {
        myModule,
        // 在这里可以引入并注册更多的模块
      },
    });
    

    请确保在modules选项中引入了你的模块,并为每个模块指定一个名称。

  3. 在组件中使用模块:

    3.1使用辅助函数

    使用mapStatemapMutationsmapActionsmapGetters等辅助函数来映射模块中的状态、mutations、actions和getters。

    // 在组件中引入Vuex
    import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
    
    export default {
      computed: {
        // 使用mapState辅助函数将模块中的state映射到组件的计算属性中
        ...mapState('myModule', ['moduleState']),
        
        // 使用mapGetters辅助函数将模块中的getters映射到组件的计算属性中
        ...mapGetters('myModule', ['moduleGetter']),
      },
      methods: {
        // 使用mapMutations辅助函数将模块中的mutations映射到组件的方法中
        ...mapMutations('myModule', ['moduleMutation']),
        
        // 使用mapActions辅助函数将模块中的actions映射到组件的方法中
        ...mapActions('myModule', ['moduleAction']),
      },
    };
    

    3.2不使用辅助函数

    可以直接通过this.$store来访问Vuex store,并通过模块的命名空间访问模块的状态、mutations、actions和getters。

    export default {
      computed: {
        // 访问模块的状态
        moduleState() {
          return this.$store.state.myModule.moduleState;
        },
        
        // 访问模块的getters
        moduleGetter() {
          return this.$store.getters['myModule/moduleGetter'];
        },
      },
      methods: {
        // 提交模块的mutations
        moduleMutation() {
          this.$store.commit('myModule/moduleMutation');
        },
        
        // 调用模块的actions
        moduleAction() {
          this.$store.dispatch('myModule/moduleAction');
        },
      },
    };
    

    在这里,'myModule/'是模块的命名空间,后面跟着具体的状态、mutations、actions和getters的名称。

3.举例说明

  1. 创建模块:store/modules 文件夹中创建两个模块,分别是 userModule.jscounterModule.js

    // store/modules/userModule.js
    const state = {
      user: null,
    };
    
    const mutations = {
      SET_USER(state, user) {
        state.user = user;
      },
    };
    
    const actions = {
      setUser({ commit }, user) {
        commit('SET_USER', user);
      },
    };
    
    const getters = {
      getUser: state => state.user,
    };
    
    export default {
      namespaced: true,
      state,
      mutations,
      actions,
      getters,
    };
    
    // store/modules/counterModule.js
    const state = {
      count: 0,
    };
    
    const mutations = {
      INCREMENT(state) {
        state.count++;
      },
    };
    
    const actions = {
      increment({ commit }) {
        commit('INCREMENT');
      },
    };
    
    const getters = {
      getCount: state => state.count,
    };
    
    export default {
      namespaced: true,
      state,
      mutations,
      actions,
      getters,
    };
    
  2. 注册模块:store/index.js 中注册这两个模块。

    // store/index.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    import userModule from './modules/userModule';
    import counterModule from './modules/counterModule';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      modules: {
        userModule,
        counterModule,
      },
    });
    
  3. 在组件中使用模块:

    3.1使用辅助函数:

    <template>
      <div>
        <div>
          <h2>User Module</h2>
          <p>User: {{ user }}</p>
          <button @click="setUser({ id: 1, name: 'John Doe' })">Set User</button>
        </div>
    
        <div>
          <h2>Counter Module</h2>
          <p>Count: {{ count }}</p>
          <button @click="increment">Increment</button>
        </div>
    
        <div>
          <h2>Getters</h2>
          <p>Get User: {{ getUser }}</p>
          <p>Get Count: {{ getCount }}</p>
        </div>
      </div>
    </template>
    
    <script>
    // 在组件中引入Vuex的辅助函数
    import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
    
    export default {
      computed: {
        // 使用mapState辅助函数将userModule的state映射到组件的计算属性中
        ...mapState('userModule', ['user']),
        
        // 使用mapState辅助函数将counterModule的state映射到组件的计算属性中
        ...mapState('counterModule', ['count']),
        
        // 使用mapGetters辅助函数将userModule的getters映射到组件的计算属性中
        ...mapGetters('userModule', ['getUser']),
        
        // 使用mapGetters辅助函数将counterModule的getters映射到组件的计算属性中
        ...mapGetters('counterModule', ['getCount']),
      },
      methods: {
        // 使用mapMutations辅助函数将userModule的mutations映射到组件的方法中
        ...mapMutations('userModule', ['SET_USER']),
        
        // 使用mapActions辅助函数将counterModule的actions映射到组件的方法中
        ...mapActions('counterModule', ['increment']),
      },
    };
    </script>
    

    3.2不使用辅助函数

    通过 this.$store 对象来访问各个模块的状态、mutations、actions 和 getters。

    // 在组件中引入Vuex
    import Vue from 'vue';
    
    export default Vue.extend({
      computed: {
        // 访问userModule的状态
        user() {
          return this.$store.state.userModule.user;
        },
        
        // 访问counterModule的状态
        count() {
          return this.$store.state.counterModule.count;
        },
      },
      methods: {
        // 提交userModule的mutations
        setUser(user) {
          this.$store.commit('userModule/SET_USER', user);
        },
        
        // 调用counterModule的actions
        increment() {
          this.$store.dispatch('counterModule/increment');
        },
        
        // 访问userModule的getters
        getUser() {
          return this.$store.getters['userModule/getUser'];
        },
        
        // 访问counterModule的getters
        getCount() {
          return this.$store.getters['counterModule/getCount'];
        },
      },
    });
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狐说狐有理

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值