computed에서 $store 접근

Web Development assistant·2024년 2월 4일
0

# Vue

목록 보기
2/4

4가지 방법이 존재하는데,

  1. 템플릿에 this.$store.state.user속성 바인딩(html tag가 지저분해 짐)
  2. computed 속성에 this.$store.state.user
  3. computed 속성에 mapState (컴포넌트에 import를 해야함, 호출도 지저분함)
  4. computed 속성에 mapGetters (store.js를 불필요하게 길게 만듬)

2번 방법이 제일 깔끔한듯

<template>
  <div> 
    <p>name : {{userInfo.id}}</p>
    <p>karma : {{userInfo.karma}}</p>
    <p>created : {{userInfo.created}}</p>
  </div>
</template>

<script>
export default {
  computed : {			
    userInfo(){
      return this.$store.state.user;
    }
  },
</script>

2번 방법의 장점: html 탬플릿 부분이 깔끔해짐. store.js에 getter 추가 안 해도 됨. 해당 컴포넌트에 따로 임포트 안 해도 됨.

만약 mapState를 쓴다면...

<script>
import { mapState } from 'vuex';	//지저분해

export default {
  computed:{
    ...mapState({		//지저분하고 명확하다는 느낌이 안 듬
      news : state => state.news
    })
  },
  created() {
    this.$store.dispatch('FETCH_NEWS');
  },
};
</script>

0개의 댓글