[Vue3실강] 7강 vuex 모듈화

youngseo·2022년 6월 10일
0
post-thumbnail

Vuex

🐥개발환경세팅

1. vuex설치 및 연결

터미널

$ npm i vuex

main.js

import { createApp } from 'vue'
import store from './store'
import App from './App.vue'
createApp(App)
  .use(store)
  .mount('#app')

store>index.js

import {createStore} from 'vuex'
export default createStore({
})

2. store에 데이터 저장

import {createStore} from 'vuex'

export default createStore({
  state() {
    return {
      count: 0
    }
  },
  getters: {

  },
  mutations: {
    increase(state) {
      state.count+=1
    }
  },
  actions: {

  }
})

3. 스토어에서 데이터가져오기

HelloWorld.vue

<template>
  <h1>{{ count }}</h1>
  <button @click="increase">
    INCREASE
  </button>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increase() {
      this.$store.commit('increase')
    }
  }
}
</script>

Brother.vue

<template>
  <h2>{{ count }}</h2>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  },
}
</script>

🐥범용화된 setState만들기

  • mutation에서는 상태에 관련된 로직만 사용하고 비동기로직X(애초안됩니다), 동기로직도 안넣는 것이 좋습니다.

index.js

  mutations: {
    setState(state, payload) {
      for(const key in payload) {
        state[key] = payload[key]
      }
    }
  },
  actions: {
    increase({state, commit}) {
      commit('setState', {
        count: state.count + 1,
        message: 'HelloWorld!'
      })
    }
  }

HelloWorld.vue

methods: {
  increase() {
    this.$store.dispatch('increase')
  }
}

🐥 Vuex 모듈화

  • 모듈화는 엄청난 기능입니다!
  • 단, namespaced를 명시해줘야한다는 단점이 있습니다.

모듈화 전 예제코드

index.js

import {createStore} from 'vuex'

export default createStore({
  state() {
    return {
      count: 0,
      message: ''
    }
  },
  getters: {

  },
  mutations: {
    setState(state, payload) {
      for(const key in payload) {
        state[key] = payload[key]
      }
    }
  },
  actions: {
    increase({state, commit}) {
      commit('setState', {
        count: state.count + 1,
        message: 'HelloWorld!'
      })
    },
    updateMessage({commit}, msg) {
      commit('setState', {
        message: msg
      })
    }
  }
})

Brother.vue

<template>
  <h2>{{ count }}</h2>
  <h2>{{ $store.state.message }}</h2>
  <button @click="$store.dispatch('updateMessage', 'Good?!')"></button>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  },
}
</script>

1. 모듈화 파일 생성

store폴더에 모듈화를 할 message.js와 count.js파일을 생성합니다.

message.js

namespaced: true옵션을 꼭 넣어줘야합니다.

export default {
  ⭐namespaced: true,state() {
    return {
      message: ''
    }
  },
  getters: {

  },
  mutations: {
    setState(state, payload) {
      for(const key in payload) {
        state[key] = payload[key]
      }
    }
  },
  actions: {
    updateMessage({commit}, msg) {
      commit('setState', {
        message: msg
      })
    }
  }
}

count.js

export default {
  namespaced: true,
  state() {
    return {
	  count: 0
    }
  },
  getters: {

  },
  mutations: {
    setState(state, payload) {
      for(const key in payload) {
        state[key] = payload[key]
      }
    }
  },
  actions: {
    increase({state, commit}){
      commit('setState', {
        count: state.count+1
      })
    }
  }
}

index.js

import {createStore} from 'vuex'
import message from './message'
import count from './count'

export default createStore({
  modules: {
    heropy: message,
    count
  }
})

💡모듈화 표기법

  • state에 접근 할 때는 점표기법을 통해 모듈화된 이름을 넣어줍니다.
    • $store.state.✅heropy.message
  • actions에 접근 할 때는 모듈화된 이름/사용할 메서드 로 표기합니다.
    • heropy/updateMessage

Brother.vue

<template>
  <h2>{{ $store.state.✅heropy.message }}</h2>
  <button @click="$store.dispatch('✅heropy/updateMessage', 'Good?!')">
    Update Message
  </button>
</template>

HelloWorld.vue

<script>
export default {
  computed: {
    count() {
      return this.$store.state.✅count.count
    }
  },
  methods: {
    increase() {
      this.$store.dispatch('✅count/increase')
    }
  }
}
</script>

🐥매핑

스토어에서 데이터를 하나 가져올 때마다 computed안에 데이터가 늘어나게 됩니다. 이를 보다 효율적으로 작성 할 수 있도록 도와주는 것이 바로 mapping을 사용할 수 있습니다.

1. state매핑(mapState)

counter.js

  state () {
    return {
      count: 0,
      double:0,
      a: '',
      b:'',
      c: ''
    }
  },

매핑하기 전 코드

<script>
export default {
  computed: {
    count() {
      return this.$store.state.count.count
    },
    double() {
      return this.$store.state.count.double
    },
    a() {
      return this.$store.state.count.a
    },
    b() {
      return this.$store.state.count.b
    },
    c() {
      return this.$store.state.count.c
    },
  },
  methods: {
    increase() {
      this.$store.dispatch('count/increase')
    }
  }
}
</script>

매핑 후 코드

<script>
import {mapState} from 'vuex'
export default {
  computed: {
    ...mapState('count', [
      'count',
      'double',
      'a',
      'b',
      'c'
    ]),
  },
  methods: {
    increase() {
      this.$store.dispatch('count/increase')
    }
  }
}
</script>

2. Actions매핑(mapActions)

<script>
import {mapState, mapActions} from 'vuex'
export default {
  methods: {
    ...mapActions('count', [
      'increase'
    ])
  }
}
</script>

0개의 댓글