Frontend-Vuejs

Vuex helpers - parent,child와 getters,mutations

jiwoolee 2021. 8. 2. 19:38

지난 게시글에 이어서 진행하자

 

 

// Parents.vue

<template>
<div id="app">
  Parent counter : {{ $store.state.counter }} <br>
  <button @click="addCounter">+</button>
  <button @click="subCounter">-</button>
  <child></child>
</div>
</template>


// Child.vue
<template>
  <div>
    <hr>
    Child counter : {{ $store.state.counter }} <br>
    <button>+</button>
    <button>-</button>
  </div>
</template>

$store.state.counter를 간단하게 바꿀거다

 

 

// Parents.vue

<template>
<div id="app">
  Parent counter : {{ Parentscounter }} <br>
  <button @click="addCounter">+</button>
  <button @click="subCounter">-</button>
  <child></child>
</div>
</template>


// Child.vue
<template>
  <div>
    <hr>
    Child counter : {{ Childcounter }} <br>
    <button>+</button>
    <button>-</button>
  </div>
</template>

이렇게!

 

그러면 Parentscounter, Childcounter가 뭔지 알려줘야겠지

Parents.vue, Child.vue에 각각 computed: {}를 추가해주자

 

// Parents.vue

<script>
import Child from "./Child.vue";

export default {
  components: {
    child: Child
  },
  computed: {
    Parentscounter(){
      return this.$store.state.counter;
    }
  },
  
  methods: {
    addCounter() {
      this.$store.state.counter++;
    },
    subCounter() {
      this.$store.state.counter--;
    }
  }
};
</script>




// Child.vue

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

 

**

computed와 methods가 많이 헷갈리는데 

이 게시글을 보고 확실하게 구분하자

 

 

 

 

 

 

 

 

 

 

 

 

 

 

이제 getter추가해보자

store.js로 이동해서 아래처럼 getters를 추가해주면 된다

  getters:{
    getCounter: function(state){
      return state.counter;
    }
  },

이렇게 하면 등록 성공

 

 

 

 

 

 

그렇다면,

이제 getters사용해보자

다시 Parents.vue, Child.vue로 이동해서 각각에 computed: {}에 수정해주면 된다

this.$store를 이용하면 getters에 접근할 수 있다

 

 computed: {
    Parentscounter(){
      return this.$store.getters.getCounter;
    }
  },
  
  
  
  computed: {
    Childcounter(){
      return this.$store.getters.getCounter;
    }
  },

** 원래 this.$store.state.counter 였는데 this.$store.getter.getCounter로 바뀜

** getCounter는 state.counter를 리턴함

 

 

 

 

 

 

 

 

 

 

이번에는 mutations를 추가해보자

store.js에 mutations를 추가해주기만 하면 된다

mutations: {
    addCounter: function (state){
      return state.counter++
    },
    subCounter: function (state) {
      return state.counter--
    }
  },

 

 

 

이제 mutations 사용

  methods: {
    addCounter() {
      this.$store.commit('addCounter');
    },
    subCounter() {
      this.$store.commit('subCounter');
      //this.$store.mutations.addCounter 이 아니라
      //commit 을 이용하여 mutations 이벤트를 호출해야 
    }
  }

 

 

 

 

 

그러면 마찬가지로,

 

 

다음에는 getters 대신 mapGetters, mutations 대신  mapMutations를 써서 더 쉽게 써보자