Vuex 2에서 초기 상태를 설정하려면 어떻게 해야 합니까?
Vue.js 2.0과 Vuex 2.0을 작은 앱으로 사용하고 있습니다.루트 컴포넌트에서와 같이 API에서 초기 상태를 검색하는 작업을 호출하여 루트 Vue 인스턴스의 '생성' 라이프 사이클 후크에 있는 저장소를 초기화합니다.
const app = new Vue({
el: "#app",
router,
store,
data: {
vacation: {},
},
components: {
'vacation-status': VacationStatus,
},
created(){
//initialize store data structure by submitting action.
this.$store.dispatch('getVacation');
},
computed: {
},
methods: {
}
});
잘 되고 있어요.제 스토어에 대한 대응은 다음과 같습니다.
getVacation({commit}){
api.getVacation().then(vacation => commit(UPDATE_VACATION, vacation))
}
이것이 'UPDATE_VACA'로 커밋하고 있는 변환'TION'은 다음과 같습니다.
[UPDATE_VACATION] (state, payload) {
state.vacation = payload.vacation;
},
문제:앱을 로드하면 스토어에서 값을 가져오는 모든 컴포넌트가 오류를 발생시킵니다. 스토어의 "정의되지 않은" 값에 액세스하려고 합니다.즉, 상태는 아직 초기화되지 않았습니다.
예를 들어, 다음과 같은 Getter가 하위 구성요소에 있는 구성요소가 있습니다.
computed: {
arrival () {
return this.$store.getters.arrival
},
departure() {
return this.$store.getters.departure
},
countdown: function() {
return this.$store.getters.countdown
}
}
상태 개체에서 'vacation'이 정의되지 않았기 때문에 이러한 모든 getter에서 오류가 발생합니다.비동기적인 문제 같지만, 틀릴 수도 있습니다.잘못된 위치에서 스토어 상태를 초기화하고 있습니까?
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
getters: {
getVacation: state => {
return state.vacation
},
guests: state => {
return state.vacation.guests
},
verifiedGuests: state => {
return state.vacation.guests.filter(guest => guest.verified)
},
emergencyContacts: state => {
return state.emergency_contacts
},
arrival: state => {
return state.vacation.check_in
},
departure: state => {
return state.vacation.check_out
},
countdown : state => {
let check_in = new Date(state.vacation.check_in);
let now = new Date();
if ((now - check_in) > 0) {
return 'This vacation started on ' + check_in;
}
let difference = check_in - now;
let day = 1000 * 60 * 60 * 24;
return Math.ceil(difference / day) + " days until your vacation";
}
},
mutations: {
[UPDATE_VACATION] (state, payload) {
state.vacation = payload.vacation;
},
[ADD_GUEST] (state, payload) {
state.vacation.guests.push(payload.guest);
},
[REMOVE_GUEST] (state, payload){
state.vacation.guests.filter(guest => { debugger; return guest.id != payload.guest.id})
},
[UPDATE_GUEST] (state, payload){
state.vacation.guests.map(guest => {
// Refactor Object.assign to deep cloning of object
return guest.id === payload.guest.id ? Object.assign({}, guest, payload.guest) : guest;
})
},
[ADD_EMERGENCY] (state, payload){
state.vacation.emergency_contacts.push(payload.emergency_contact)
},
[REMOVE_EMERGENCY] (state, payload){
state.vacation.emergency_contacts.filter(contact => contact.id !== payload.emergency_contact.id)
},
[UPDATE_EMERGENCY] (state, payload){
state.vacation.emergency_contacts.map(contact => {
// Refactor not needed because emergency_contact is a shallow object.
return contact.id === payload.emergency_contact.id ? Object.assign({}, contact, payload.emergency_contact) : contact;
});
}
},
actions: {
getVacation({commit}){
api.getVacation().then(vacation => commit(UPDATE_VACATION, vacation))
},
addGuest({commit}, guest){
commit(ADD_GUEST, guest);
},
removeGuest({commit}, guest){
commit(REMOVE_GUEST, guest);
},
updateGuest({commit}, guest){
commit(UPDATE_GUEST, guest);
},
addEmergency({commit}, guest){
commit(ADD_EMERGENCY, contact)
},
removeEmergency({commit}, contact){
commit(REMOVE_EMERGENCY, contact)
},
updateEmergency({commit}, contact){
commit(UPDATE_EMERGENCY, contact)
},
updateServer(store, payload){
return api.saveVacation(payload)
}
}
});
솔루션이 다른 사람들에게 명확해지도록 하기 위해:
나는 가게 자체에서 내 초기 상태를 제대로 설정하지 못했다.데이터를 가져와 스토어를 올바르게 업데이트하고 있었는데 스토어를 다음과 같이 초기화해야 했습니다.
export default new Vuex.Store({
state: {
vacation: {}//I added this, and then justed updated this object on create of the root Vue Instance
},
});
난 네가 모든 것을 잘 하고 있다고 생각해.getters를 올바르게 작성하지 않은 것일 수 있습니다(코드에서 정의를 찾을 수 없습니다).또는 초기 상태가 올바르게 설정되어 있지 않을 수도 있습니다(스니펫에도 표시되지 않습니다).
나는 사용할 것이다.mapState
컴포넌트에서 상태 속성을 사용할 수 있습니다.
데모에서 간단히 추가users
의 배열로mapState
method 파라미터와 사용자 데이터는 컴포넌트에서 사용할 수 있습니다.(getter를 방금 추가했습니다)users
어떻게 작동하는지 보여줘야지mapState를 사용하는 경우에는 필요하지 않습니다.)
아래 데모나 이 바이올린을 봐주세요.
const api =
'https://jsonplaceholder.typicode.com/users'
const UPDATE_USERS = 'UPDATE_USERS'
const SET_LOADING = 'SET_LOADING'
const store = new Vuex.Store({
state: {
users: {},
loading: false
},
mutations: {
[UPDATE_USERS](state, users) {
console.log('mutate users', users)
state.users = users;
console.log(state)
}, [SET_LOADING](state, loading) {
state.loading = loading;
}
},
getters: {
users(state) {
return state.users
}
},
actions: {
getUsers({commit}) {
commit(SET_LOADING, true);
return fetchJsonp(api)
.then((users) => users.json())
.then((usersParsed) => {
commit(UPDATE_USERS, usersParsed)
commit(SET_LOADING, false)
})
}
}
})
const mapState = Vuex.mapState;
const Users = {
template: '<div><ul><li v-for="user in users">{{user.name}}</li></ul></div>',
computed: mapState(['users'])
}
new Vue({
el: '#app',
store: store,
computed: {
...mapState(['loading']),
//...mapState(['users']),
/*users () { // same as mapState
return this.$store.state.users;
}*/
users() { // also possible with mapGetters(['users'])
return this.$store.getters.users
}
},
created() {
this.$store.dispatch('getUsers')
},
components: {
Users
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.0.5/fetch-jsonp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.min.js"></script>
<div id="app">
<div v-if="loading">loading...</div>
<users></users>
<pre v-if="!loading">{{users}}</pre>
</div>
초기 상태를 반환하는 함수를 생성하여 다음과 같이 Vuex 인스턴스에서 사용할 수 있습니다.
function initialStateFromLocalStorage() {
...
const empty = {
status: '',
token: '',
user: null
}
return empty;
}
export default new Vuex.Store({
state: initialStateFromLocalStorage,
...
스테이트 오브젝트를 반환하는 즉시 그 기능 안에서 원하는 것을 할 수 있는 거죠?
언급URL : https://stackoverflow.com/questions/41835716/how-do-i-set-initial-state-in-vuex-2
'programing' 카테고리의 다른 글
MySQL에서 특수 문자를 이스케이프하려면 어떻게 해야 합니까? (0) | 2022.10.04 |
---|---|
하나의 쿼리에서 두 테이블에서 삭제 (0) | 2022.10.04 |
django 모델의 사용자 지정 테이블 생성 옵션 (0) | 2022.10.04 |
Rsync MariaDB 데이터 폴더 도커 세이프? (0) | 2022.10.04 |
where 절과 order_by에 대한 MYSQL 인덱스를 만듭니다. (0) | 2022.10.04 |