vuex的辅助函数

1、辅助函数:

通过辅助函数mapStatemapActionsmapMutations,把vuex.store中的属性映射到vue实例身上,这样在vue实例中就能访问vuex.store中的属性了,对于操作vuex.store就很方便了。

state辅助函数为mapState,actions辅助函数为mapActions,mutations辅助函数为mapMutations。(Vuex实例身上有mapState、mapActions、mapMutations属性,属性值都是函数)

2、如何使用辅助函数

在当前组件中引入Vuex

通过Vuex来调用辅助函数

3、辅助函数如何去映射vuex.store中的属性

1、mapState:把state属性映射到computed身上

4、mapGetters:把getters属性映射到computed身上

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./vue.js"></script>
    <script src="./vuex.js"></script>
    <style>
      .add {
        border: 1px solid red;
      }

      .show {
        border: 1px solid pink;
        margin-top: 20px;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <add></add>
      <show></show>
    </div>

    <script>
      let { mapState, mapGetters, mapMutations, mapActions } = Vuex;
      let store = new Vuex.Store({
        state: {
          count: 10,
        },
        getters: {
          getCount(state) {
            return state.count;
          },
        },
        mutations: {
          add(state) {
            state.count = state.count + 1;
          },
        },
      });
      let add = {
        template: `
            <div>
                <button @click="add">添加</button>  
            </div>
        `,
        methods: {
          ...mapMutations(["add"]),
        },
      };
      let show = {
        template: `
            <div>
                展示数据    {{ count }}
            </div>
        `,
        computed: {
          ...mapState(["count"]),
        },
      };
      let app = new Vue({
        el: "#app",
        components: {
          add,
          show,
        },
        store,
      });
    </script>
  </body>
</html>


版权声明:本文为weixin_59519449原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。