"Vuex actions"의 두 판 사이의 차이

3번째 줄: 3번째 줄:
;Vuex 액션
;Vuex 액션
* 액션은 변이(mutation)와 유사한데, 다른 점은...
* 액션은 변이(mutation)와 유사한데, 다른 점은...
** 상태를 변이시키는 대신 액션으로 변이에 대한 커밋을 한다.
** 상태를 직접 변이시키는 대신 액션으로 변이에 대한 커밋을 한다.
** 작업에는 임의의 비동기 작업이 포함될 수 있다.
** 작업에는 임의의 비동기 작업이 포함될 수 있다.



2020년 9월 28일 (월) 16:33 판

1 개요

Vuex actions
Vuex 액션
  • 액션은 변이(mutation)와 유사한데, 다른 점은...
    • 상태를 직접 변이시키는 대신 액션으로 변이에 대한 커밋을 한다.
    • 작업에는 임의의 비동기 작업이 포함될 수 있다.

2 예제 1 - context 사용

  • 액션 increment는 context를 받는다.
  • Vue에서는 dispatch 메소드로 increment 액션을 호출한다.
<div id="app">
  <span>{{ count }}</span>
  <button @click="increment">+</button>
</div>

<script src="//unpkg.com/vue"></script>
<script src="//unpkg.com/vuex"></script>
<script>
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increment() {
      this.$store.dispatch('increment')
    }
  }
})
</script>

3 예제 2 - commit 사용

  • 액션 increment는 commit을 받는다.
  • Vue에서는 dispatch 메소드로 increment 액션을 호출한다.
<div id="app">
  <span>{{ count }}</span>
  <button @click="increment">+</button>
</div>

<script src="//unpkg.com/vue"></script>
<script src="//unpkg.com/vuex"></script>
<script>
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment ({ commit }) {
      commit('increment')
    }
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increment() {
      this.$store.dispatch('increment')
    }
  }
})
</script>

4 같이 보기

5 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}