vuex中关于mapState,mapGetters,mapMutations,mapActions的作用

来源:互联网 发布:手机熊猫登录网络 编辑:程序博客网 时间:2024/05/18 01:41


在开始接触vuex框架的时候对那些state,action,mutation,getter等理解的还挺顺利的,然后突然出来一种加了一个前缀的mapState等,这样的就有点蒙圈了。。。特别是官方的文档并没有给除详细的说明跟例子。。。然后就自己慢慢理解了一下。其实也就是一个重命名而已。。。以下就是例子,希望能帮助理解:

在store中代码

[html] view plain copy
  1. import Vuex from 'vuex'  
  2. import Vue from 'vue'  
  3. Vue.use(Vuex);  
  4. const store = new Vuex.Store({  
  5.   state: {  
  6.     count: 10,  
  7.     numb: 10086  
  8.   },  
  9.   getters: {  
  10.     add: (state, getter) => {  
  11.       state.count = getter.add;  
  12.       return state.count;  
  13.     },  
  14.   },  
  15.   mutations: {  
  16.     increment(state,){  
  17.         state.count += 2;  
  18.     },  
  19.   },  
  20.   actions: {  
  21.     actionA({ dispatch, commit }) {  
  22.       return commit('add');  
  23.     },  
  24.   }  
  25. });  
  26.   
  27. export default store;  


在调用的模块里面的代码如下:

[html] view plain copy
  1. <template>  
  2.   <div class="hello">  
  3.     <button @click="increment">加{{count}}</button>  
  4.   </div>  
  5. </template>  
  6.   
  7. <script>  
  8.   import {mapState,mapActions} from 'vuex'  
  9.   
  10.   export default {  
  11.     name: 'hello',  
  12.     data () {  
  13.       return {  
  14.         msg: 'Welcome to Your Vue.js App'  
  15.       }  
  16.     },  
  17.     methods:{  
  18.       increment(){  
  19.         this.$store.dispatch('incrementsync').then(() => {  
  20.           console.log('then');  
  21.         });  
  22.       }  
  23.     },  
  24.     computed: mapState({ // mapState相当于映射  
  25.         count: 'numb',  //这个时候count应该等于多少?!! 是等于store文件里面的count呢还是等于numb?答案是等于numb!这边的意思是mapState把'numb'的值映射给了count,所以count等于10086  
  26.     })  
  27.   }  
  28. </script>  
这个时候按钮应该显示加10还是显示加10086?答案是加10086,所以map其实就是一个在store文件中的映射而已,就是不用让你要调用一个值需要敲这么多代码:this.$state.count;而只需要用count。。。

界面效果:


好了,其他的mapAction,mapMutations的原理是一样样的

原创粉丝点击