ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [vue] vuex binding helper - vue store 사용하기
    프론트엔드/Vuejs 2021. 6. 25. 15:23

    vue 에서 vuex 를 사용하여 store 를 만들면,

    getters 의 경우 this.$store.getters.[getter이름] 로 사용가능

    actions 의 경우 this.$store.dispatch(‘[action이름]’, data) 과 같이 사용할 수 있다.

    또는 직접 state 에 바로 접근해서 this.$store.state.book.message 로도 사용가능은 하다.

     

    helper 없이 기본적으로 사용

    <template>
      <div id="app">
        <div>
          <label>{{getMsg}}</label>
    
          <br/>
    
          <button @click="onChangedMsg">Click</button>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'app',
      computed: {
        getMsg () {
          return this.$store.getters.getMsg
        }
      },
      methods: {
        onChangedMsg () {
          this.$store.dispatch('callMutation', { newMsg: 'World !!' })
        }
      }
    }
    </script>

     

    store/index.js

    store 를 하나만으로는 사용하기 어려우므로 기능별 또는 페이지별로 분리해야한다.

    기능/페이지별로 store를 분리하고, 하나의 store에는 state, mutations, actions, getters를 포함해서 관리하는게 편하다.

    index 파일에서 여려개의 모듈을 import 하는 역할이다.

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    import BookStore from './module/book'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
        modules: {
            book: BookStore
        }
    })

    store/module/book.js

    // state
    const state = {
        message: 'Hello'
    }
    
    // mutations
    const mutations = {
         changeMessage (state, newMsg) {
          state.message = newMsg
        }
    }
    
    // actions
    const actions = {
        callMutation ({ state, commit }, { newMsg }) {
          commit('changeMessage', newMsg)
        }
    }
    
    // getters
    const getters = {
        getMsg (state) {
          return `${state.message} => Length : ${state.message.length}`
        }
    }
    
    export default {
      state,
      mutations,
      actions,
      getters
    }

    위와 같이 한 페이지별 기능별로 js 파일을 따로 모듈로 관리하여 둔다면 관리하기 편하다.

     

    Vuex Binding Helper

    위에 설명했던 예시처럼 사용할 수도 있지만 vuex 에는 binging helper 라는 util 이 존재하여 좀 더 간편하게 사용이 가능하다.

     

    Helper는 state, mutations, actions, getters 별로 각각 mapState, mapActions, mapMutations, mapGetters가 존재하고 아래처럼 바인딩할 수 있다.

     

    import { mapState, mapActions, mapMutations, mapGetters } from 'vuex'
    
    export default {
      name: 'Sample',
      computed: {
        ...mapState('book', {
            message: state => state.message     // -> this.message
        }),
        ...mapGetters('book', [
           'getMsg'       // -> this.getMsg
        ])
      },
      methods: {
        ...mapMutations('book', [
            'mutation이름'     // -> this.mutation이름() 으로 mutation 접근
        ]),
        ...mapActions('book', [
            'action이름'      // -> this.action이름() 으로 action call가능
        ])
      }
    }

     

    Vuex createNamespacedHelpers

    mapHelper를 통해 개발이 가능하지만 좀 더 편리하고 효율적으로 하기 위해서는 createNamespacedHelpers를 사용하는 것이 좋다. 어떻게 보면 결과적으로나 사용되는 Util은 동일하다.

     

    import { createNamespacedHelpers } from 'vuex'
    
    const 
        bookHelper = createNamespacedHelpers('book'),
        bookListHelper = createNamespacedHelpers('bookList')
    
    export default {
      name: 'Sample',
      computed: {
        ...bookHelper.mapState({
            message: state => state.message     // -> this.message
        }),
        ...bookHelper.mapGetters([
           'getMsg'       // -> this.getMsg
        ]),
        ...bookListHelper.mapState({
            messageList: state => state.messageList     // -> this.messageList
        }),
        ...bookListHelper.mapGetters([
           'getMsgList'       // -> this.getMsgList
        ])
      },
      methods: {
        ...bookHelper.mapMutations([
            'changeMessage'     // -> this.changeMessage()
        ]),
        ...bookHelper.mapActions([
            'callMutation'      // -> this.callMutation()
        ]),
        ...bookListHelper.mapMutations([
            'changeMessageList'     // -> this.changeMessageList()
        ]),
        ...bookListHelper.mapActions([
            'callMutationList'      // -> this.callMutationList()
        ]),
      }
    }

     

    반응형

    댓글

Designed by Tistory.