여러 컴포넌트에 공유되는 데이터의 속성
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,
})
main.js
import 추가...
import { store } from './store/index'
...
new Vue({
store,
...
}).$mount('#app')
[ Vuex UI 결과 ]
//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 결과 ]
//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 ]