[ Vue Project ] - Vuex [ mapState ]

yooni·2021년 8월 26일
0

project

목록 보기
8/11
post-thumbnail

[ Vuex 공식문서 ]

# Vuex - 상태관리 도구

여러 컴포넌트에 공유되는 데이터의 속성

1.npm i vuex 설치
2. store 폴더 생성 > store 내용작성

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

Vue.use(Vuex);

export const store = new Vuex.Store({
    state:{
        news: []
    },
    // getters,
    // mutations,
    // actions,
})
  1. main.js import 추가
...
import { store } from './store/index'
...

new Vue({
  store,
  ...
}).$mount('#app')

[ Vuex UI 결과 ]


[ Vuex 다이어그램 ]

  • state -
  • actions -
  • mutations -

# actions & mutations

//store
mutations:{
  SET_NEWS(state, news){
    state.news = news;
  }
},
  actions:{
    FETCH_NEWS({ commit }){
      fetchNewsList()
        .then(({ data }) => {
        commit('SET_NEWS', data);
      })
        .catch(Error)
    }
  }
//NewsView
<template>
    <div>
        <div v-for="user in this.$store.state.news" :key="user.id">{{ user.title }}</div>
    </div>
</template>
<script>
    export default {
        name: "NewsView",
        created() {
            this.$store.dispatch("FETCH_NEWS");
        }
    }
</script>

[ 정상적인 UI 결과 ]


# mapState - 반복 정리

//AskView.vue
<template>
    <div>
        <div v-for="item in fetchedask" :key="item.id">{{ item.title }}</div>
    </div>
</template>
<script>
    import { mapState } from 'vuex';
    export default {
        name: "AskView",
        computed: {
            ...mapState({
                fetchedask: state => state.ask
            })
            // ask(){
            //     return this.$store.state;
            // }
        },
        created() {
            this.$store.dispatch('FETCH_ASK');
        }
    }
</script>

[ 실행 결과 UI ]


[ vue-project Github - Vuex ]

profile
그리듯 성장하는 기쁨의 한걸음. -2021.07

0개의 댓글