getters对state中的数据进行再处理,类似于计算属性

一、设置getters

  1. export default new Vuex.Store({
  2. state: {
  3. count:0
  4. },
  5. ...
  6. getters:{
  7. myCount(state){
  8. return `当前计数为:${state.count}`
  9. }
  10. }
  11. })

二、获取getters中的数据

2-1 直接获取

  1. <h3>{{this.$store.getters.myCount}}</h3>

2-2 mapGetters

  1. <template>
  2. <div class="home">
  3. <h1>首页</h1>
  4. <h2>{{count}}</h2>
  5. <h3>{{myCount}}</h3>
  6. </div>
  7. </template>
  8. <script>
  9. import {mapState,mapGetters} from 'vuex';
  10. export default {
  11. name: 'home',
  12. computed:{
  13. ...mapState(['count']),
  14. ...mapGetters(['myCount'])
  15. }
  16. }
  17. </script>