vuex로 todolist 리팩토링 ▼
solm-blog.tistory.com/13?category=858024
vue.js Todolist 만들기 [vuex 리팩토링] --3
Vuex로 해결할 수 있는 문제 1. MVC 패턴에서 발생하는 구조적 오류 2. 컴포넌트 간 데이터 전달 명시 3. 여러 개의 컴포넌트에서 같은 데이터를 업데이트 할 때 동기화 문제 vuex 라이브러
solm-blog.tistory.com
Helper함수를 사용하여 vuex 속성들을 더 쉽게 사용해보자.
-state -> mapState
-getters - > mapGetters
-mutations -> mapMutations
-actions -> mapActions
1. store.js
export const store = new Vuex.Store({
state : {
todoItems : storage.fetch()
},
getters : {
storedTodoItems(state){
return state.todoItems;
}
},
)}
todoItems를 쉽게 불러오기 위해 getters에 선언해둠
2. List.vue
<template>
<div id="listApp">
<!-- fontawesome CDN-->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css"
/>
<!-- list 출력 -->
<div v-if="this.storedTodoItems.length <= 0" class="ListIsEmpty"> 작성된 List가 없습니다. <br> List를 작성해주세요. </div>
<ul v-for="(todoItem, index) in this.storedTodoItems" :key="todoItem.title" class="ShowTodoList">
<li><i class="fas fa-check" @click="toggleBtn(todoItem, index)" :class="{finishToo : todoItem.completed}"></i></li>
<li :class="{finish : todoItem.completed}">{{todoItem.title}}</li>
<li><i class="fas fa-trash-alt" @click="OneTodoItemDel({todoItem, index})" ></i></li>
<br>
</ul>
</div>
</template>
<script>
import{mapGetters, mapMutations} from 'vuex'
export default {
methods : {
...mapMutations({
// helper함수는 인자를 선언안해도 호출하는 부분에 인자가 있으면 자동으로 인자값을 넘겨줌
// 다만, 호출하는 부분에 인자가 두개일 경우 객체 형태로 {} 만들어줘야 함
OneTodoItemDel : 'removeOneItem'
}),
toggleBtn(todoItem){
todoItem.completed = !todoItem.completed;
localStorage.removeItem(todoItem.title);
localStorage.setItem(todoItem.title, JSON.stringify(todoItem));
}
},
computed : {
...mapGetters(['storedTodoItems'])
// ...mapGetters({
//배열로 사용하지 않고 객체로 사용할때는 getters이름과 컴포넌트에서 사용 할 이름이 다를때 사용
//})
},
}
(1) mapGetters를 import해주고 computed로 mapGetters의 메소드를 불러와 사용해줌
사용 예시)
<ul v-for="(todoItem, index) in this.storedTodoItems" :key="todoItem.title" class="ShowTodoList">
(2) Mutation 코드 줄이기
* 두개 모두 메소드 선언 후 메소드 안에서 사용
mapMutation 사용하기 전 코드)
OneTodoItemDel(todoItem, index){
this.$store.commit('removeOneItem', {todoItem, index}); },
mapMutations 사용 후 코드)
...mapMutations({ OneTodoItemDel : 'removeOneItem' }),
* 사용할 때 주의점 :
helper함수는 인자를 선언안해도 호출하는 부분에 인자가 있으면 자동으로 인자값을 넘겨줌
다만, 호출하는 부분에 인자가 두개일 경우 객체 형태로 {} 만들어줘야 함
ex) @click="OneTodoItemDel({todoItem, index})"
'SPA > Vue' 카테고리의 다른 글
vuejs 라우터 설치 및 구현 (0) | 2021.05.10 |
---|---|
Vue CLI 2.x / CLI 3.x 비교 (0) | 2021.05.10 |
vue.js Todolist 만들기 [vuex 리팩토링] --3 (0) | 2021.05.10 |
vue.js Todolist 만들기 [컴포넌트 통신O] --2 (0) | 2021.05.07 |
vue.js ToDoList 만들기 [컴포넌트 통신X] --1 (0) | 2021.05.07 |