이안의 평일코딩

[Vue] Vuex(4) - computed, mapState, mapMutations, mapActions 본문

Front-end/Vue

[Vue] Vuex(4) - computed, mapState, mapMutations, mapActions

이안92 2021. 5. 19. 13:53
반응형

 computed와 map

 

methods vs computed

 

함수를 만들 때 methods :{}가 아닌 computed : {}를 사용해보자.

export default {
  name: 'App',
  data(){
    return {
      counter : 0,
    }
  },
  methods: {
    now(){
      return new Date()
    },
  },
  computed: {
    now2(){
      return new Date()
    },
  },
}
</script>

methods 함수는 사용할 때마다 실행되지만, computed 함수는 사용해도 실행되지 않는다.

계산결과 저장용 함수로 쓸 수 있고 자원절약이 된다.

 

<template>
  <p>{{now()}} {{counter}}</p>
  <p>{{now2}} {{counter}}</p> // computed 함수는 이름만 쓴다
  <button @click="counter++">버튼</button>
</template>

버튼을 누르면 counter는 1씩 증가하지만, methods 함수 now()는 counter와 함께 매 새로운 시간을 출력하고,

computed 함수 now2는 처음 출력한 시간이 계속 유지되고 counter만 증가한다.

즉, computed는 처음 실행된 후 값을 간직한다.

methods와 달리 computed 함수는 ()없이 이름만 쓴다.

 

그리고 store.js에 있는 데이터도 computed 안에 넣으면 꺼내쓸 때 편하다. (return과 this. 이용)

computed: {
  name(){
    return this.$store.state.name
  },
  age(){
    return this.$store.state.age
  },
}

위와 같이 넣은 다음 template에서 $store.state.name이 아닌 {{name}}과 같이 꺼내쓸 수 있다.

<p>{{$store.state.name}} {{name}}</p>

 

mapState

 

위의 computed함수를 보면 name과 age의 데이터를 저장하는 코드가 너무 길기때문에 mapState를 이용하면 state 꺼내쓰는 코드가 짧아진다.

 

먼저, mapState를 vuex에서 import 해온 뒤 ...mapState를 이용하면 된다.

<script>
import {mapState, mapMutations} from 'vuex';

export default {
  name: 'App',
  computed: {
    ...mapState(['name', 'age', 'likes']),
    ...mapState({ myName: 'name', }),
  },
}
</script>

...mapState(['state명'])으로 computed 함수에 기록한 뒤 {{name}}과 같이 출력할 수 있다.

그리고 오브젝트 자료도 입력이 가능하며, ({작명: 'name',})와 같이 쓰자. 마찬가지로 {{작명}}으로 불러온다.

 

mapMutations

 

vuex mutations을 한번에 꺼내쓰려면 methods 함수에 ...mapMutations(['함수명'])을 쉽게 사용할 수 있다.

mapState와 마찬가지로 먼저 vuex에서 import 해온 뒤 사용한다.

 

store.js
import axios from 'axios';
import { createStore } from 'vuex'

const store = createStore({
    state () {
        return {
            more : {},
            age : 20,
        }
    },
    mutations :{
        setMore(state, data){
            state.more = data
        },
        add(state, data){
            state.age += data
        },
    },
})

export default store;

store.js의 mutations 함수에 setMore, add과 같은 함수를 정의한다.

 

App.vue
<template>
  <p>{{age}}</p>
  <button @click="$store.commit('add', 10)">버튼</button>
  <button @click="add(10)">버튼</button>
</template>

<script>
import {mapState, mapMutations} from 'vuex';

export default {
  name: 'App',
  methods: {
    ...mapMutations(['setMore', 'add']),
  },
}
</script>

그리고 정의한 함수를 methods에 ...mapMutations(['함수명'])으로 데려온다.

그럼 "$store.commit('함수명')"이라고 쓰던 것을 "함수명"으로 간편하게 사용할 수 있다.

데이터를 전달하고 싶을때는 "$store.commit('함수명', data)"을 "함수명(data)"로 쓰자.

 

mapState, mapMutations와 마찬가지로 mapActions도 동일하게 사용하면 된다.

반응형
Comments