관리 메뉴

샐님은 개발중

Vuex #2 mapGetters,mapState 사용법 본문

카테고리 없음

Vuex #2 mapGetters,mapState 사용법

샐님 2021. 9. 12. 09:28
728x90
반응형

store.js

getters 를 통해 미리 계산된 값을 정의해 놓는다.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { //data
 	allUsers:[
          {userId: 'hoza123', password: '123', name: 'Hoza', address: 'Seoul', src:'https://goo.gl/oqLfJR'},
          {userId: 'max123', password: '456', name: 'Max', address: 'Berlin', src:'https://goo.gl/Ksk9B9'},
          {userId: 'lego123', password: '789', name: 'Lego', address: 'Busan', src:'https://goo.gl/x7SpCD'}
        ]
  },
  getters:{ //computed .함수에서 state를 쓴다고 선언해줘야함.
	allUsercount:function(state){
		return state.allUsers.length
	},
	countOfSeoul: state =>{
			let count =0;
		state.allUsers.forEach(user =>{
			if(user.address=='Seoul') count ++
			
		})
			return count
		
	},
	percentOfSeoul :(state,getters) =>{
	  return	Math.round(getters.countOfSeoul / getters.allUsercount * 100) //math.round : 소수점 반올림
	}
	
},
  mutations: {

  },
  actions: {

  }
})

users.vue

<template>
  <div>
    <h1>All Users: {{count}}</h1>
    <h1>Seoul Users: {{seoul}}({{percent}}%)</h1 <!-- 3.가져온 getters를 사용함 -->
    <v-list two-line>
      <v-list-tile 
        v-for="(user, index) in allUsers"
        :key="index"
        avatar
      >
        <v-list-tile-avatar color="grey lighten-3">
          <img :src="user.src">
        </v-list-tile-avatar>

        <v-list-tile-content>
          <v-list-tile-title v-html="user.name"></v-list-tile-title>
          <v-list-tile-sub-title>id:#{{index}} / {{user.address}} 嫄곗<</v-list-tile-sub-title>
        </v-list-tile-content>
      </v-list-tile>
    </v-list>

  </div>
</template>

<script>
import { EventBus } from '@/main.js'
import { mapState,mapGetters } from 'vuex' // 1.vuex 에서 mapstate,mapgetters 를 가져옴

  export default {
    data() {
      return {
       
      }
    },
    computed:{ // 2.store에서 선언한 getters를 가져옴
/*     ...mapGetters(['allUsercount','percentOfSeoul','countOfSeoul']) */
 		...mapGetters({count:'allUsercount',percent:'percentOfSeoul',seoul:'countOfSeoul'}),
    	...mapState(['allUsers'])
    },
    mounted() {
      EventBus.$on('signUp', users => { 
        this.$store.state.allUsers.push(users)
      })
    }
  }
</script>

 

728x90
반응형