Vuex?
컴포넌트의 depth가 깊어질수록 컴포넌트끼리 데이터를 전달하는게 쉽지않음. 따라서 하나의 저장소(store)에서 손쉽게 관리할 수 있도록 나온 vuejs 라이브러리다.
사용법
vuex 설치
npm install vuex --save
src/api/index.js
import axios from 'axios';
const config = {
baseUrl: 'https://my-backand-server.com/api'
}
function fetchArticle() {
return axios.get(`${config.baseUrl}/article`);
}
function fetchReply() {
return axios.get(`${config.baseUrl}/reply`);
}
export {
fetchArticle,
fetchReply,
}
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import { getArticle, getReply } from '../api/index.js';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
article: [],
articleReply: []
},
actions: {
FETCH_ARTICLE(context) {
getArticle()
.then(response => {
context.commit('SET_ARTICLE', response.data);
})
.catch(error => {
console.log(error);
});
},
FETCH_REPLY(context) {
getReply()
.then(response => {
context.commit('SET_REPLY', response.data);
})
.catch(error => {
console.log(error);
});
},
},
mutations: {
SET_ARTICLE(state, article) {
state.article = article;
},
SET_ASKS(state, reply) {
state.articleReply = reply;
},
}
})
ㄴ vuex 라이브러리 import
ㄴ state : vuex 저장소에서 관리할 데이터들
ㄴ actions : action에서는 API를 통해 데이터를 가져오는 작업만을 한다.
ㄴ mutations : actions에서 context.commit()을 하면 선언된 mutations에서 state에 값을 할당한다.
src/views/ArticleView.vue
<template>
<div>
<p v-for="item in articles" :key="item.id">
<a :href="item.url">{{ item.title }}</a>
</p>
</div>
</template>
<script>
export default {
computed: {
articles() {
// store내의 state 데이터까지 접근하는데 너무 변수가 길어짐. 따라서 컴포넌트에서 보기좋게 사용하기위해 computed에 선언
return this.$store.state.article;
}
},
created() {
// vuex 저장소에 선언된 actions(FETCH_ARTICLE) 실행
this.$store.dispatch('FETCH_ARTICLE');
}
}
</script>
<style>
</style>
'개발' 카테고리의 다른 글
[웹기초] 프록시를 알아보자 (0) | 2020.09.23 |
---|---|
[웹기초] HTTP 메시지 정의, 흐름, 구성 (0) | 2020.09.19 |
VMWare 및 Centos8 ISO 다운로드 (0) | 2020.09.10 |
git 수정후 되돌리기 (commit전, commit 후, push 후) (0) | 2020.03.06 |
Docker를 사용하기 위해 알아야하는 인프라와 네트워크에 관한 기초 지식 (1) | 2018.12.18 |