[Vue] mapState, mapGetters, mapMutations, mapActions 정리

[Vue] mapState, mapGetters, mapMutations, mapActions 정리

mapState

  • Vuex에 선언한 state 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
// App.vue
import { mapState } from 'vuex'

computed() { 
  ...mapState(['num'])
  // num() { return this.$store.state.num; }
}

// store.js
state: {
  num: 10
}

------ .vue ------

<!-- <p>{{ this.$store.state.num }}</p> -->
<p>{{ this.num }}</p>


mapGetters

  • Vuex에 선언한 getters 속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapGetters } from 'vuex'

computed() { ...mapGetters(['reverseMessage'])}

// store.js
getters: {
  reverseMessage(state) {
    return state.msg.split('').reverse().join('');
  }
}

-------- .vue --------


<!-- <p>{{ this.$store.getters.reverseMessage }}</p> -->
<p>{{ this.reverseMessage }}</p>

mapMutations

  • Vuex에 선언한 mutations 속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapMutations } from 'vuex'

methods: {
  ...mapMutations(['clickBtn']),
  authLogin() {},
  displayTable() {}
}

// store.js
mutations: {
  clickBtn(state) {
    alert(state.msg);
  }
}

--------- .vue ----------

<button @click="clickBtn"> popup message </button>

mapActions

  • Vuex에 선언한 actions 속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapActions } from 'vuex'

methods: {
  ...mapActions(['delayClickBtn']),
}

// store.js
actions: {
  delayClickBtn(context) {
    setTimeout(() => context.commit('clickBtn'), 2000);
  }
}

--------- .vue ----------

<button @click="delayClickBtn"> delay popup message </button>


출처

댓글

이 블로그의 인기 게시물

[Python] # -*- coding: utf-8 -*-를 쓰는 이유

[소프트웨어공학] NS(Nassi-Schneiderman) 차트

[컴퓨터네트워크] Telnet이란?