# actions

์•ก์…˜(actions)์€ ๋ฎคํ…Œ์ด์…˜ ์ค‘์—์„œ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ๋กœ์ง๋“ค์„ ์ •์˜ํ•˜๋Š” ์†์„ฑ์ž…๋‹ˆ๋‹ค. ๋™๊ธฐ ์ฒ˜๋ฆฌ๋Š” ๋ฎคํ…Œ์ด์…˜, ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๋Š” ์•ก์…˜์œผ๋กœ ์ดํ•ดํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค. ํ˜น์‹œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ์— ๋Œ€ํ•ด์„œ ์ž˜ ๋ชจ๋ฅด์‹œ๋Š” ๋ถ„๋“ค์€ ์ด ๊ธ€ (opens new window)์„ ์ฐธ๊ณ ํ•˜์„ธ์š”.

# actions ์„ ์–ธ

์•ก์…˜์„ ์ •์˜ํ•˜๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค. ์•ž ๋ฎคํ…Œ์ด์…˜ ์ฑ•ํ„ฐ์—์„œ ์‚ดํŽด๋ดค๋˜ ์ฝ”๋“œ๋ฅผ ์‚ด์ง ๋ฐ”๊ฟ”๋ดค์Šต๋‹ˆ๋‹ค. ๋ฎคํ…Œ์ด์…˜ ์ฝ”๋“œ์—์„œ๋Š” ์ปดํฌ๋„ŒํŠธ ๋‹จ์—์„œ commit('reverseMessage') API๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ state ์†์„ฑ์— ์ •์˜๋˜์–ด ์žˆ๋˜ ์ƒํƒœ ๊ฐ’์„ ๋ณ€ํ™˜ํ–ˆ์Šต๋‹ˆ๋‹ค.

new Vuex.Store({
  state: {
    message: ''
  },
  mutations: {
    reverseMessage(state, data) {
      state.message = data.split('').reverse().join('');
    }
  },
  actions: {
    fetchMessage(context) {
      axios.get(url).then(function(response) {
        context.commit('reverseMessage', response.message);
      });
    }
  }
})

์ด๋ฒˆ์—๋Š” ์ปดํฌ๋„ŒํŠธ ๋‹จ์—์„œ ์•ก์…˜์„ ํ˜ธ์ถœํ•˜๊ณ  ๋‚˜๋ฉด fetchMessage() ๋ผ๋Š” ์•ก์…˜ ๋ฉ”์„œ๋“œ๊ฐ€ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค. fetchMessage() ๋ฉ”์„œ๋“œ๋Š” HTTP ํ†ต์‹ ์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋น„๋™๊ธฐ ์ฝ”๋“œ๊ฐ€ ๋˜๊ณ , GET ์š”์ฒญ์˜ ์‘๋‹ต์œผ๋กœ ์˜จ ๊ฐ’์„ ๋ฎคํ…Œ์ด์…˜์˜ ์ธ์ž๋กœ ๋„˜๊ฒจ์„œ ์—ญ์ˆœ์œผ๋กœ ๋ณ€ํ™˜ํ•œ ๋‹ค์Œ์— message ์ƒํƒœ ๊ฐ’์— ๋‹ด์•„์ค๋‹ˆ๋‹ค.

# actions ํ˜ธ์ถœ

์•ก์…˜์„ ์ปดํฌ๋„ŒํŠธ์—์„œ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

new Vue({
  methods: {
    getMessage() {
      this.$store.dispatch('fetchMessage');
    }
  }
})

getMessage() ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ์•ก์…˜์˜ fetchMessage() ์†์„ฑ ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค.