Vue

[Vue2] vue Vuex Actions

양치개발자 2023. 5. 23. 16:08
반응형

Vuex Action란?

  • 비동기 작업을 수행한다.
  • 상태 변이(mutations)를 일으키는 메서드들을 호출한다.
  • 외부 데이터와의 상호작용을 처리하는 역할을 합니다.

 

예시

index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
	actions: {
        addTodo({commit}, value) {
            // 비동기 함수인 setTimeout으로 2초 후에 생성
            setTimeout( function(){
                commit('ADD_TODO', value); // commit 메소드 필요, ADD_TODO함수의 value사용
            },500)
        },
        toggleTodo({commit}, payload) {
            setTimeout( function(){
                commit('TOGGLE_TODO', payload); // commit 메소드 필요, ADD_TODO함수의 value사용
            },500)
        },
        deleteTodo({commit}, todoId){
            setTimeout( function(){
                commit('DELETE_TODO', todoId); // commit 메소드 필요, ADD_TODO함수의 value사용
            },500)
        },
    },
})

 

AddTodo.vue

<script>
	methods: {
            // todo 추가 함수
            addTodo(e) {
                // dispatch를 이용을 한다.
                this.$store.dispatch('addTodo', e.target.value);
                this.todoText = ''; // input값 빈 값
            }
        }
</script>

 

Todo.vue

<script>
	methods: {
        // checkbox 함수
        toggleCheckbox(e) {
            this.$store.dispatch('toggleTodo', {
                id: this.todo.id,
                checked: e.target.checked
            })
       	},
            clickDelete() {
                this.$store.dispatch('deleteTodo', this.todo.id)
               }
    	}
</script>

 

Axios 사용법

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. Serving ~2 billion requests each month.

jsonplaceholder.typicode.com

위 사이트에서 임의의 데이터를 받을 수 있습니다.

// 뷰에서 권고하는 HTTP 통신 라이브러리
// NPM 방식
$ npm i axios

 

라이브러리를 설치하고 나면 axios라는 변수에 접근할 수 있게 됩니다. 

axios 변수를 이용하여 아래와 같이 HTTP GET 요청을 날리는 코드를 작성합니다.

 

UserLis.vue

<template>
    <div>
        User List
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        created() {
            axios.get('https://jsonplaceholder.typicode.com/users').then(res => {
                console.log(res);
            });
            const a = 1;
            console.log(a);
        }
    }
</script>

실행 화면

axois가 비동기이기 때문에 코드를 먼저 써도 나중에 인식이 된다.

 

 

<template>
    <div>
        User List
        <div v-for="user in users" :key="user.id">
            {{ user.name }}
        </div>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                users: []
            }
        },
        created() {
            // axios 호출
            axios.get('https://jsonplaceholder.typicode.com/users').then(res => {
                this.users = res.data;
            });
        }
    }
</script>

 

실행 화면

최종 코드

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

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 },
        ],
        // axios의 users 데이터
        users: []
    },
    mutations: { 
        // users 값을 가지고 오는 것
        SET_USERS(state, users) {
            state.users = users;
        },
        // 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: {
        // axios를 호출 하는 함수
        getUsers({commit}) {
                axios.get('https://jsonplaceholder.typicode.com/users').then(res => {
                commit('SET_USERS',res.data);
            });
        },
        addTodo({commit}, value) {
            // 비동기 함수인 setTimeout으로 2초 후에 생성
            setTimeout( function(){
                commit('ADD_TODO', value); // commit 메소드 필요, ADD_TODO함수의 value사용
            },500)
        },
        toggleTodo({commit}, payload) {
            setTimeout( function(){
                commit('TOGGLE_TODO', payload); // commit 메소드 필요, ADD_TODO함수의 value사용
            },500)
        },
        deleteTodo({commit}, todoId){
            setTimeout( function(){
                commit('DELETE_TODO', todoId); // commit 메소드 필요, ADD_TODO함수의 value사용
            },500)
        },

    },
    getters: {

    }
})

 

App.js

<template>
  <div id="app" class="container">
    <h1 class="text-center">Todo App</h1>
    <CompletedTodo />
    <AddTodo />
    <hr>
    <TodoList />
    <UserList />
  </div>
</template>

<script>
import TodoList from '@/components/TodoList.vue';
import AddTodo from '@/components/AddTodo.vue';
import CompletedTodo from '@/components/CompletedTodo.vue';
import UserList from './components/UserList.vue';
export default {
  components: {
    TodoList,
    AddTodo,
    CompletedTodo,
    UserList
  },
  
}
</script>

UserList.js

<template>
    <div>
        User List
        <div v-for="user in users" :key="user.id">
            {{ user.name }}
        </div>
    </div>
</template>

<script>
    export default {
        created() {
            this.getUsers();
        },
        computed: {
            users() {
                return this.$store.state.users;
            }
        },
        methods: {
            getUsers() {
                this.$store.dispatch('getUsers')
            }
        }
    }
</script>

실행 화면

 

참고 영상

https://tinyurl.com/4s42cmr2

 

뷰js 2 (Vue.js 2) 기초 익히기 기본 강좌!

안녕하세요 코지 코더입니다. 이번 시리즈는 뷰js 2 Vue.js 2 기초 익히기인데요 html, css 그리고 javascript 기본을 공부하신 분이 보면 유용한 시리즈입니다.

www.youtube.com

 

반응형