ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Vue2] vue Vuex Getters & Map 헬퍼
    Vue 2023. 5. 25. 18:22
    반응형

    <script>
    	// map 헬퍼를 사용하기 위해서 불러옴
        import { mapState } from 'vuex';
        export default {
            created() {
                this.getUsers();
            },
            computed: {
            	// ...mapState(['불러올 요소'])
                 ...mapState([
                    'todos',
                    "users"
                ]),
            },
            methods: {
                getUsers() {
                    this.$store.dispatch('getUsers')
                }
            }
        }
    </script>

    Vuex Getters

    : computed 처럼 state값이 변경될때 특정 상태를 계산할 수 있도록 사용하는 속성

     

    특징

    Vuex 스토어의 state(상태) 객체를 첫 번째 인자로 받아 사용됩니다.

    이를 통해 상태 데이터에 접근할 수 있으며, 필요한 데이터를 반환하는 역할을 합니다.

    Getters는 Vuex 스토어에 선언된 getters 속성에 객체 형태로 정의됩니다.

     

    예시

    store > index.js

    import Vue from 'vue';
    import Vuex from 'vuex';
    import axios from 'axios';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
        getters: {
            // computed랑 같은 개념
            numberOfCompletedTodo : state => {
                return state.todos.filter(todo => todo.checked).length;
            }
        }
    })

    CompletedTodo.vue

    <script>
    export default {
        // todo를 checked하면 그 갯수를 보여주는 것
        computed: {
            // todos 값을 store의 state의 값을 찾으면 된다.
            // todos() {
            //     return this.$store.state.todos;
            // },
            numberOfCompletedTodo() { 
            	// store 안에 getters 속성 안에 numberOfCompletedTodo라는 함수 호출
                return this.$store.getters.numberOfCompletedTodo;
            }
        }
    }
    </script>

    Todo.vue

    <template>
        <div class="mb-2 d-flex">
            <div>
                <input type="checkbox" :checked="todo.checked" @change="toggleCheckbox">
            </div>
            <!-- todo.checked클래스가 true 이면 text-muted 실행 아니면 '' -->
            <!-- todo.checked클래스가 true 이면 text-decoration : line-throug 실행 아니면 '' -->
            <span class="ml-3 flex-grow-1"
                :class="todo.checked ? 'text-muted' : ''" 
                :style="todo.checked ? 'text-decoration : line-through' : ''"
            >
                {{ todo.text }}
            </span>
                <button
                class="btn btn-danger btn-sm "
                @click="clickDelete"
                >Delete</button>
                {{ numberOfCompletedTodo }}
        </div>
    </template>
    
    <script>
    export default { 
        computed : {
            numberOfCompletedTodo() {
                return this.$store.getters.numberOfCompletedTodo;
            }
        },
    }
    </script>

    실행 화면

     

    Map 헬퍼

     

     

    UserList.vue

    script>
        import { mapState, mapActions } from 'vuex';
        export default {
            created() {
                this.getUsers();
            },
            computed: {
                ...mapState(['users'])
                // users() {
                //     return this.$store.state.users;
                // },
                // todos() {
                //     return this.$store.state.todos;
                // }
            },
            methods: {
                ...mapActions(['getUsers'])
            }
        }
    </script>

    - 내가 호출하고 싶은 요소를 불러올 때, computed에서 호출 할 이름을 추가를 계속 해야되는데

    부분을 좀 더 쉽게 할라고 map 헬퍼를 사용을 한다.

    - 다른 map 함수를 쓸 수도 있다.

     

    ...map함수 ([]) 로도 쓸 수 있지만 객체 대신에 배열로도 가능하다.

    <template>
        <div>
            User List
            <div v-for="user in people" :key="user.id">
                {{ user.name }}
            </div>
        </div>
    </template>
    
    <script>
        import { mapState, mapActions } from 'vuex';
        export default {
            created() {
                this.getUsers();
            },
            computed: {
                ...mapState({people : 'users'})
                // users() {
                //     return this.$store.state.users;
                // },
                // todos() {
                //     return this.$store.state.todos;
                // }
            },
            methods: {
                ...mapActions(['getUsers'])
            }
        }
    </script>

     

     

     

    참고 영상

    https://tinyurl.com/4scb3mwv

     

    반응형

    'Vue' 카테고리의 다른 글

    [Vue2] Vue Vuex Modules  (0) 2023.05.31
    [Vue2] vue Vuex Actions  (0) 2023.05.23
    [Vue2] Vue Vuex Mutations  (0) 2023.05.22
    [Vue2] Vue Vuex State  (0) 2023.05.19
    [Vue2] Vue Vuex 준비 및 설치  (0) 2023.05.18

    댓글

Designed by Tistory.