본문 바로가기

Vue.js

[Udemy Vue 완벽가이드 Section15] 214. 상태에 컴포넌트 연결하기

# $store.state를 통해 state 접근

메서드를 추가해서 버튼을 연결할 수 있다.

'Add 1' 버튼을 클릭하면 트리거되는 'addOne'메서드를 추가해보자.

 

method내에서 this.$store.state에 액세스하면 state인 counter가 있다.

그 counter를 ++로 증가해주자.

<template>
  <base-container title="Vuex">
    <h3>{{ $store.state.counter }}</h3>
    <button @click="addOne">Add 1</button>
  </base-container>
</template>

<script>
import BaseContainer from './components/BaseContainer.vue';

export default {
  components: {
    BaseContainer,
  },
  methods: {
    addOne() {
      this.$store.state.counter++;
    },
  },
};
</script>

 

 

## $store.state 값을 computed에 아웃소싱

h3태그의 $store.state.counter값을 computed 프로퍼티를 써서 아웃소싱하는 방법도 있다.

computed에 counter 프로퍼티를 추가해서 this.$store.state.counter를 반환해보자.

이제 이 counter를 h3태그에 가져다 쓰고 저장한 다음, 'Add 1'버튼을 클릭하면 Vuex의 도움을 받아 업데이트된다.

<!--App.vue-->
<template>
  <base-container title="Vuex">
    <h3>{{ counter }}</h3>
    <button @click="addOne">Add 1</button>
  </base-container>
</template>

<script>
import BaseContainer from './components/BaseContainer.vue';

export default {
  components: {
    BaseContainer,
  },
  computed: {
    counter() {
      return this.$store.state.counter;
  },
  methods: {
    addOne() {
      this.$store.state.counter++;
    },
  },
};
</script>

 

 

Vuex는 이보다 더 많은 것을 제공한다.

여기선 Vuex와 Vuex 상태의 작동 원리를 아주 간단히 설명했다.

 

 

TheCounter.vue라는 컴포넌트를 만들어보자.

여기에 App.vue에 작성한 h3태그와 computed 프로퍼티를 옮겨와보자.

그리고 TheCounter.vue컴포넌트를 App.vue에 등록하자.

<!--TheCounter.vue-->
<template>
  <h3>{{ counter }}</h3>
</template>
<script>
export default {
  computed: {
     counter() {
       return this.$store.state.counter;
     },
  },
};
</script>
<!--App.vue-->
<template>
  <base-container title="Vuex">
    <the-counter></the-counter>
    <button @click="addOne">Add 1</button>
  </base-container>
</template>

<script>
import BaseContainer from './components/BaseContainer.vue';
import TheCounter from './components/TheCounter.vue';

export default {
  components: {
    BaseContainer,
    TheCounter, //지역컴포넌트 등록
  },
  methods: {
    addOne() {
      this.$store.state.counter++;
    },
  },
};
</script>

 

저장 후, 확인하면 전과 동일하게 작동한다.

 

 

inject나 props 전달 없이도 모든 컴포넌트에서 액세스할 수 있는 전역 저장소 전역 상태이기 때문이다.

물론, state가 props를 아주 대체하진 않는다.

부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 때는 여전히 props가 유효하다.

하지만 위 counter처럼 전체적인 애플리케이션 state에는 아무 추가 설정 없이도 바로 state를 이용할 수 있으므로 Vuex가 아주 유용하다.

 

** 출처: 모든 내용은 Udemy Vue-완벽가이드 강의를 기반으로 작성하였습니다.