• 理解Vuex的辅助函数mapState


    参考的地址是: https://www.cnblogs.com/tugenhua0707/p/9794423.html
    之所以会在这里记录下来,是为了方便自己以后忘记的时候查看学习而已~;
    并没有别的意思~;
    如果想看详细版本
    去这里:https://www.cnblogs.com/tugenhua0707/p/9794423.html
    作者写的很详细的~

    当我们的组件需要获取多个状态的时候,
    将这些状态都声明为计算属性会有些重复和冗余,为了解决这个问题,
    我们可以使用mapState的辅助函数来帮助我们生成计算属性。
    
    mapState函数返回的是一个对象,
    我们需要使用一个工具函数将多个对象合并为一个,
    这样就可以使我们将最终对象传给computed属性。
    

    store/state.js 代码如下:

    export default {
      add: 0,
      errors: '',
      counts: 0
    };
    

    store/mutations.js 代码如下:

    import * as types from './mutations-types';
    
    export default {
      [types.ADD] (state, payload) {
        state.add = payload;
      },
      [types.SETERROR] (state, payload) {
        state.errors = payload;
      },
    
      [types.COUNTASYNC] (state, payload) {
        state.counts = payload;
      }
    }
    

    store/mutations-types.js 代码如下:

    // 新增list
    export const ADD = 'ADD'; 
    
    // 设置错误提示
    export const SETERROR = 'SETERROR';
    
    // 异步操作count
    export const COUNTASYNC = 'COUNTASYNC';
    

    store/index.js 代码如下:

    import Vue from 'vue'
    import Vuex from 'vuex'
    import state from './state'
    import mutations from './mutations'
    import * as getters from './getters'
    import * as actions from './actions'
    
    Vue.use(Vuex)
    export default new Vuex.Store({ 
        state,
        mutations,
        actions,
        getters
    });
    

    home.vue 在mounted生命周期打印一下 console.log(this);

    <template>
      <div></div>
    </template>
    <script type="text/javascript">
      export default {
        data() {
          return {
            
          }
        },
        methods: {
          
        },
        mounted() {
          console.log(this);
        }
      }
    </script>
    

    如上代码,我们使用 mapState工具函数会将store中的state映射到局部计算属性中。
    我们在mounted方法内,直接使用 this.xx 即可使用到对应computed中对应的属性了。也就是 我们使用 this.add 就直接映射到 this.$store.state.add 了 。
    当然mapState也可以接受一个数组,如下简单代码:

    computed: {
      /*
      ...mapState({
        add: state => state.add,
        counts: state => state.counts
      })
      */
      ...mapState([
        'add',
        'counts'
      ])
    },
    mounted() {
      console.log(this);
    }
    

    可以看到,接受数组也是可以的,在mounted生命周期内,我们直接可以使用 this.add 或 this.counts 可以获取到值了。

    切记:mapState的属性的时候,一定要和state的属性值相对应,也就是说 state中定义的属性值叫add,那么mapState就叫add,如果我们改成add2的话,就获取不到add的值了

  • 相关阅读:
    win10安装.net 3.5无法启动服务,原因可能是已被禁用或与其相关联的设备没有启动
    配置SQL用户访问指定表,指定列
    GNU Gettext for Delphi, C++ and Kylix
    Delphi 7 中使用IdUDPServer1和IdUDPClient1控件实现通信检测
    xp不能安装NET Framework4.0解决方法
    基于TCP的Socket连接【Delphi版】
    牛客网优惠码
    GitHub基本操作
    xdb-test
    设置本地yum源
  • 原文地址:https://www.cnblogs.com/IwishIcould/p/13728376.html
Copyright © 2020-2023  润新知