• mitt
    • npm install mitt
    • import {createApp} from 'vue'
      import App from './App.vue'
      import mitt from 'mitt'
      
      const emitter = mitt()
      const app = createApp(App)
      app.config.globalProperties.emitter = emitter
      
      app.mount('#app')
    • main.js파일에 mitt을 import해준 후 globalProperties.emitter에 mitt을 넣어줍니다.
    • 사용법
      • 데이터 전송
        • this.emitter.emit('이벤트 명', data)
      • 데이터 수신
        • this.emitter.on('이벤트 명', data => {
          	// data안에 수신한 데이터가 들어있음
          })
  • vuex
    • https://next.vuex.vuejs.org/ 참고
    • npm install vues@next --save
    • store.js파일 생성
      • import {createStore} from 'vuex'
        
        const store = createStore({
        	state() {
            	return {
                	name : 'kade'
                }
            }
        })
        
        export default store
      • state() == data() 이렇게 생각하면 됩니다.
      • 사용법
        • <template>
          
          	<h1>{{$store.state.name}}</h1>
              <!-- kade출력 -->
          
          </template>​
    • main.js에 store.js등록
      • import store from './store.js'
        
        app.use(store).mount('#app')
    • store에 있는 state는 외부에서 변경이 가능하지만 그렇게 변경을 하게되면 어디에서 변경이 일어났는지 추적이 어려움
    • 유지보수 혹은 디버깅등을 위해 데이터 수정을 위한 함수를 정의하면 된다
      • mutations
        • const store = createStore({
          	state() {
              	return {
                  	isClick : false
                  }
              },
              mutations : {
              	clickFunc(state, data) {
                  	//data에는 전송받은 데이터가 들어있음
                  	state.isClick = !state.isClick
                  }
              }
          })
      • 사용법
        • <template>
          
          	<h1>{{$store.state.isClick}}</h1>
          	<button @click="$store.commit('clickFunc', '전송할 데이터가 있으면 넣어줌')">click</button>
              
          </template>
    • ajax, axios등 서버로부터 데이터를 요청해야 할 경우 actions에 함수를 만들어주면 된다
      • const store = createStore({
        	state() {
            	return {
                	name : 'kade'
                    age : 0
                }
            },
            mutations : {
            	nameChange(state, changedName) {
                	state.name = changedName
                },
                ageChange(state, changedAge) {
                	state.name = changedAge
                }
            },
            actions : {
            	getAgeFromServer(context) {
                	axios.get('URL')
                    	.then(data => {
                        	context.commit('nameChange', data.age)
                        })
                }
            }
        })
      • 컴포넌트에서 actions안에 함수 호출 방법
        • $store.dispatch('함수 명')
  • mapState, computed, composition, pwa등 추가 기능도 있다...

'Front-end > Vue.js' 카테고리의 다른 글

LocalStorage, token  (0) 2021.11.06
8. axios  (0) 2021.11.04
7. vue router - 3  (0) 2021.11.04
6. vue router - 2  (0) 2021.11.04
5. vue router - 1  (0) 2021.11.04

+ Recent posts