반응형
- 구조
//https://vuex.vuejs.org/kr/guide/structure.html
- api
index.js (vuejs-axios-공통 참고)
- store
ㄴ index.js
ㄴ state.js
ㄴ actions.js
ㄴ mutations.js
ㄴ getters.js
- main.js
//main.js
import Vue from 'vue'
import router from './router'
import App from './App.vue'
import store from './store'
new Vue({
el:'#app',
router,
store,
render: h => h(App)
})
- index.js
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
})
const {token} = localStorage
store.commit('LOGIN',token)
export default store
- actions.js
//actions.js
import * as api from '../api'
const actions = {
LOGIN ({commit},{email,password}){
return api.auth.login(email,password)
.then(({accessToken}) => commit('LOGIN', accessToken)
},
ADD_USER(_,{name}){
return api.user.create(name)
},
FETCH_USERS({commit}){
return api.user.fetch().then(data => {
commit('SET_USERS',data.list)
})
}
}
export default actions
- getters.js
//getters.js
const getters = {
isAuth(state){
return !!state.token
}
}
export default getters
- mutations.js
//mutations.js
import {setAuthInHeader} from '../api'
const mutations = {
LOGIN(state,token){
if(!token) return
state.token = token
localStorage.setItem('token',token)
setAuthInHeader(token)
},
LOGOUT(state){
state.token = null
delete localStorage.token
setAuthInHeader(null)
},
SET_IS_ADD_USER(state,toggle){
state.isAddUser = toggle
},
SET_USERS(state,users){
state.users = users
}
}
export default mutations
- actions.js
//actions.js
import * as api from '../api'
const actions = {
login({ commit }, {email, password}){
return api.auth.login(email, password)
.then(({accessToken}) => commit('LOGIN',accessToken))
},
ADD_USER(_, {title}) {
return api.users.create(title)
},
FETCH_USER({commit}) {
return api.user.fetch().then(data => {
commit('SET_USERS',data.list)
})
}
}
export default actions
- state.js
//state.js
const state = {
token: null,
isAddUser: false,
users: [],
}
export default state
- sample
//sample.vue
import {mapState, mapMutations,mapActions} from 'vuex'
export default {
data(){
loading: false,
error: '',
},
created(){
this.fetchUserData()
},
computed: {
...mapState([
'isAddUser',
users: 'users'
])
},
methods: {
...mapMutations([
'SET_IS_ADD_USER'
]),
...mapActions([
'ADD_USER',
'FETCH_USERS'
]),
fetchUserData(){
this.loading = true
this.FETCH_USERS().finally(_=>{
this.loading = true
})
},
addUser(){
this.SET_IS_USER(false)
this.ADD_USER({name: this.input}).then()=>{
this.FETCH_USERS()
}
}
}
}
출처: 인프런 강좌
반응형
'Front' 카테고리의 다른 글
vuejs-axios - 공통 처리 방법 (0) | 2020.08.10 |
---|