Vue - Vuex

김종민·2023년 3월 13일
0

Vue의 상태관리를 위해 Vuex를 사용한다.

  1. store.js 혹은 store.ts파일을 만들어 아래의 코드를 작성한다.
import { createStore } from 'vuex'

const store = createStore({
  state(){
    return {
      globalState : "This is GlobalState!!"
    }
  },
})

export default store
  1. main.js 혹은 main.ts에 다음을 추가한다.
import store from './store.js'
app.use(store).mount('#app')
  1. state를 수정하기 위해선 직접적으로 수정하지 말고 mutations를 사용한다.
import { createStore } from 'vuex'

const store = createStore({
  state(){
    return {
      globalState : "This is GlobalState!!"
    }
  },
    mutations :{
    stateChange(state){
      state.globalState = "State Change !!"
    }
  },
})

export default store
<button @click="$store.commit('stateChange')">버튼</button>
  1. 만약 state가 ajax요청(비동기)에 의해 변경되는 경우에는 actions을 사용한다
import { createStore } from 'vuex'

const store = createStore({
  state(){
    return {
      globalState : "This is GlobalState!!"
    }
  },
    mutations :{
    stateChange(state){
      state.globalState = "State Change !!"
    }
  },
  actions : {
  getData(context){
    axios.get('').then(()=>{ 
      context.commit("stateChange")
    })
  }
}
})

export default store
profile
개발을 합시다 :)

0개의 댓글