-
[Vue2] Vue Vuex MutationsVue 2023. 5. 22. 15:25반응형
Vuex Mutations란?
Mutations 이란 Vuex 의 데이터, 즉 state 값을 변경하는 로직들을 의미한다.
Mutations의 특징
- 인자를 받아 Vuex 에 넘겨줄 수 있다.
- computed 가 아닌 methods에 등록을 해야 된다.
Mutations의 사용 방법
매개변수.$store.commit('mutation에 있는 함수명', '화면에 보여줄 값'); 매개 변수가 없을 시에는 mutation에 있는 값을 이용을 해도 된다.
예시
App.vue에 있는 method 데이터를 store의 index.js 안으로 이동
// App.js <script> methods: { } </script>
// store > index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { todos: [ {id:1, text:'buy a car', checked:false }, {id:2, text:'play game', checked:false }, ] }, mutations: { // todo 추가하는 함수 ADD_TODO(state, value) { state.todos.push({ id: Math.random(), // id를 랜덤으로 돌림 text: value, // text는 input의 값임 checked : false // checked는 flase값 고정 }); }, // flase로 된 checkbox를 true로 바꾸기 TOGGLE_TODO(state, {id,checked}) { const index = state.todos.findIndex(todo => { return todo.id === id; }); state.todos[index].checked = checked; }, // todo 삭제 함수 DELETE_TODO(state, todoId) { const index = state.todos.findIndex(todo => { return todo.id === todoId; }); state.todos.splice(index,1); } }, actions: { }, getters: { } })
AddTodo.vue
<script> methods: { // todo 추가 함수 addTodo(e) { // store에서 ADD_TODO 함수를 커밋을 해서 e.target.value 값을 보여준다. this.$store.commit('ADD_TODO', e.target.value); this.todoText = ''; // input값 빈 값 // this.$emit('add-todo', e.target.value); } } </script>
TodoComponent.vue
<script> methods: { // checkbox 함수 toggleCheckbox(e) { this.$store.commit('TOGGLE_TODO', { id: this.todo.id, checked: e.target.checked }) }, // 클릭하면 지우는 함수 clickDelete() { this.$store.commit('DELETE_TODO', this.todo.id); } } </script>
Store > index.js 안에 함수를 선언을 하고 각 컴포넌트에서 $store.commit('함수명', 화면에 나오는 값)
으로 호출 후 사용을 하면 된다.
참고 영상
뷰js 2 (Vue.js 2) 기초 익히기 기본 강좌!
안녕하세요 코지 코더입니다. 이번 시리즈는 뷰js 2 Vue.js 2 기초 익히기인데요 html, css 그리고 javascript 기본을 공부하신 분이 보면 유용한 시리즈입니다.
www.youtube.com
반응형'Vue' 카테고리의 다른 글
[Vue2] vue Vuex Getters & Map 헬퍼 (0) 2023.05.25 [Vue2] vue Vuex Actions (0) 2023.05.23 [Vue2] Vue Vuex State (0) 2023.05.19 [Vue2] Vue Vuex 준비 및 설치 (0) 2023.05.18 [Vue2] vue 미니 프로젝트 ToDo App 2 (0) 2023.05.17