[vue] mapState, mapGetters 그리고 computed, method

Yeong·2023년 6월 27일

컴포넌트 단에서 스토어의 state를 가장 쉽게 접근하는 방법은 mapState가 맞다만, 스토어의 state를 컴포넌트에서 접근하는 방법이 아래와 같이 몇 가지가 있다.

  1. 템플릿에 this.$store.state.user속성 바인딩
  2. computed 속성에 this.$store.state.user
  3. computed 속성에 mapState
  4. computed 속성에 mapGetters

😍mapGetters

component의 computed 역할. 코드를 줄여서 작성 가능하다.

store.js에 있는 state값을 가져오는 것이다.

//store.js

export default new Vuex.Store({
  state: {//데이터
    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'}
    ]
  },
  getter:{
    allUsersCount: function(state){
      // 어떠한 값을 쓸건지 인자로 선언해준다.
      return state.allUsers.length
    },
    countOfSeoul: state => {
      let count = 0
      state.allUsers.forEach(user => {
        if(user.address === 'Seoul') count++
      });
      return count
    },
    percenOfSeoul: (state, getters) => {
      return Math.round(getters.countOfSeoul / getters.allUsersCount * 100)
    }
  },
})

그리고 template에서 반복되는 문구를 줄여 사용할 수 있다.

<template>
	<h1>All Users{{ allUsersCount}}</h1>
    <h1>Seoul Users{{ countOfSeoul}} ({{percentOfSeoul}}%)</h1>
</template>

<script>
import {mapGetters} from 'vuex'

  export default {
    data() {
      return {
    },
    computed: {
      ...mapGetters(['allUsersCount', 'countOfSeoul', 'percentOfSeoul'])
    },
  }
</script>

정리하자면 !!

  1. script 부분에 mapGetters 선언
import { mapGetters } from 'vuex'
  1. export default 부분에 computed 추가 (앞에 … 써주는건 규칙)

    computed: {
    ...mapGetters(['allUsersCount', 'countOfSeoul', 'percentOfSeoul'])
    },

  2. template 부분이 간단하게 써도 잘 작동한다.

    ```
    <h1>All Users({{allUsersCount}})</h1>
    <h3>Seoul Users({{countOfSeoul}})({{percentOfSeoul}}%) </h3>
    ```

    3-1. 이것도 귀찮다면 다음과 같이 작성한다.

    ```
    computed: {
          ...mapGetters({
            count: 'allUsersCount',
            seouls: 'countOfSeoul',
            percent: 'percentOfSeoul'
          })
    ```
    template부분이 더 간단해진 것을 볼수 있다.
    
        <h1>All Users({{count}})</h1>
        <h3>Seoul Users({{seouls}})({{percent}}%)</h3>

😍mapState

  1. script 부분에 mapstate import
import { mapState, mapGetters } from 'vuex'
  1. computed부분에 mapstate 추가
 computed: {
      ...mapGetters({
        count: 'allUsersCount',
        seouls: 'countOfSeoul',
        percent: 'percentOfSeoul'
      }),
      ...mapState(['allUsers'])
    },
  1. 이랬던 코드가
      <v-list-tile 
        v-for="(user, index) in $store.state.allUsers"
        :key="index"
        avatar
      >
  1. 다음과 같이 간결해진 것을 볼수 있다.

    <v-list-tile 
        v-for="(user, index) in allUsers"
        :key="index"
        avatar>
    

💡 computed 와 methods 속성의 차이점

methods 속성은 호출될 때만 해당 로직이 수행되고,
computed 속성은 대상 데이터의 값이 변경되면 자동적으로 수행된다는 것입니다.
즉, 수동적으로 데이터를 갱신하느냐, 능동적으로 데이터를 갱신하느냐 !

복잡한 연산을 반복 수행해서 화면에 나타내야 한다면 computed속성을 이용하는 것이 methods 속성을 이용하는 것보다 성능 면에서 효율적이다.

0개의 댓글