About

Vuex는 Vue.js 애플리케이션을 위한 상태 관리 패턴 + 라이브러리 입니다 . 

 

 

 

 

기본 형식

 

 

 

const Counter = {
  // state
  data () {
    return {
      count: 0
    }
  },
  // view
  template: `
    <div>{{ count }}</div>
  `,
  // actions
  methods: {
    increment () {
      this.count++
    }
  }
}

createApp(Counter).mount('#app')
  • Vuex 는 react의 redux와 같은 기능이다.
  • 주의할 점은 상태를 새로고침 시 상태가 초기화 된다는 점이다. 
  • 대안으로는 'vuex-persistedstate' 나 ( state - localstorage 동기화 라이브러리) 같은 또 다른 라이브러리가 필요하다.

 

 

Mutation

- Vuex 스토어에서 실제로 상태를 변경하는 유일한 방법은 돌연변이를 커밋하는 것입니다.

 

const store = createStore({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // mutate state
      state.count++
    }
  }
})

 

- store.commit Mutation 핸들러를 호출하려면 해당 유형으로 호출해야 합니다 .

store.commit('increment')

 

 

 

 

 

 

 

 

Getter

const store = createStore({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos (state) {
      return state.todos.filter(todo => todo.done)
    }
  }
})

 

 

- Helper 'mapGetters'는 저장소 getter를 로컬 계산 속성에 매핑합니다.

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

 

 

Action

- Action은 Mutation와 일치하며 차이점은 다음과 같습니다.

  • 상태를 변경하는 대신 action을 변경합니다.
const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

 

 

 

store.dispatch('increment')

 

 

참고

 

https://vuex.vuejs.org/

'IT > Vue' 카테고리의 다른 글

[Vue] Vue로 간단한 사이트 제작  (0) 2023.10.14

+ Recent posts