Vuex 설치하기
1. 다음 명령어를 입력한다.
npm install --save vuex
2. store/index.js 안에서 vuex 를 사용할 수 있다.
import Vue from 'vue' import Vuex from 'Vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { //data 데이터 }, mutations: { //데이터를 실질적으로 바꾸는 역할 }, actions: { //methods 함수 }, getters: { //computed 역할 } });
*접근방법
mutations 은 commit
actions 은 dispatch
예)
this.$store.dispatch('toggleTodo', { id : this.todo.id, checked : e.target.checked })
index.js
import Vue from 'vue' import Vuex from 'vuex'; import axios from 'axios'; Vue.use(Vuex); export default new Vuex.Store({ state: { //data 데이터 todos: [ { id: 1, text: "buy a car", checked: false }, { id: 2, text: "paly a game", checked: true }, { id: 3, text: "buy a gg", checked: false }, ], users: [] }, mutations: { //데이터를 실질적으로 바꾸는 역할 ADD_TODO(state, value) { state.todos.push({ id: Math.random(), text: value, checked: false }); }, TOGGLE_TODO(state, { id, checked }) { const index = state.todos.findIndex(todo => { return todo.id === id; }); state.todos[index].checked = checked; }, DELETE_TODO(state, todoId) { const index = state.todos.findIndex(todo => { return todo.id === todoId; }); state.todos.splice(index, 1); }, SET_USERS(state, users) { state.users = users; } }, actions: { //methods 함수 addTodo({ commit }, value) { setTimeout(() => { commit('ADD_TODO', value); }, 500); }, toggleTodo({ commit }, payload) { setTimeout(() => { commit('TOGGLE_TODO', payload); }, 500); }, deleteTodo({ commit }, todoId) { setTimeout(() => { commit('DELETE_TODO', todoId); }, 500); }, getUsers({ commit }) { axios.get('https://jsonplaceholder.typicode.com/users',).then( res => { console.log(res.data); commit('SET_USERS', res.data); }); } }, getters: { //computed 역할 numberOfCompletedTodo: state => { return state.todos.filter(todo => todo.checked).length; } } });
댓글 ( 4)
댓글 남기기