Post

[Vue] methods, computed / vueX mapState, mapMutations

[Vue] methods, computed / vueX mapState, mapMutations

computed

vue에서 함수 만들 때 methods 또는 computed 함수 안에 만들 수 있다.
methods와 computed가 다른 점

methods에 선언된 함수는 호출될 때 마다 실행됨
computed에 선언된 함수는 호출해도 다시 실행되지 않음. 컴포넌트 로드 시 한번 실행 후 그 값을 계속 저장해서 사용함
computed는 일종의 계산결과 저장공간이라고 보면 된다. (자원절약)
computed 내 함수는 return 값이 꼭 있어야 한다.
computed 내 함수는 호출 시 소괄호 없이 함수명만 사용한다.
computed를 사용하면 state 꺼내는 코드가 짧아진다.

예제1

1
2
3
4
5
6
7
8
9
10
11
12
13
export default {
  name:'App',
  methods: {
    now(){  // 호출 시 마다 실행됨
      return new Date();  // 현재시간
    }
  },
  computed:{
    now2(){  // 로드 시 한 번 실행됨
      return new Date();  // 현재시간
    }
  },
}

예제2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export default {
  name:'App',
  data(){
    return {
      name: 'kim',
      age: 20,
    }
  },
  computed:{
    name(){
      return this.$store.state.name;
    },
    age(){
      return this.$store.state.age;
    }
  },
}
1
<p>{{ name }}<p>	// kim 출력

mapState

store에 있는 data를 쉽게 가져다 쓸 수 있는 함수
mapState를 사용하면 state 꺼내 쓰는 코드가 짧아진다.
computed 안에서 사용하는게 일반적이다.

1
import { mapState } from 'vuex'
1
2
3
computed:{
	...mapState(['post']),	// store data명
},
1
2
<!-- <p>$store.state.post[idx].liked</p> -->
<p>post[idx].liked</p>

mapMutations

methods 에서 store mutations data를 한번에 꺼내쓸 수 있다.

1
import { mapMutations, mapState } from 'vuex'
1
2
3
methods: {
  ...mapMutations(['setAddPost']),  // store mutations 함수 이름
},
1
2
// this.$store.commit('setAddPost', newPost);
this.setAddPost(newPost); // mapMutations

mapActions

도 있음

This post is licensed under CC BY 4.0 by the author.