2016-11-03 2 views
1

이제 Vuex를 배우기 시작했습니다. 지금까지 나는 store.js 파일에 공유 데이터를 저장하고 모든 모듈에 store을 가져오고 있지만 이것은 성가 시게되고 있으며 상태를 변경하는 것에 대해 걱정하고 있습니다.Vuex로 비동기 호출하기

저는 Vuex를 사용하여 Firebase에서 데이터를 가져 오는 방법에 대해 고심하고 있습니다. 내가 알고있는 것에서 만 액션이 비동기 호출을 할 수 있지만 변형 만이 상태를 업데이트 할 수 있습니까?

지금은 내 mutations 객체에서 firebase를 호출하고 있습니다. 정상적으로 작동하는 것으로 보입니다. 솔직히 모든 컨텍스트, 커밋, 디스패치 등은 약간 과부하 상태입니다. Vuex를 생산적으로 사용하는 데 필요한 최소량 만 사용하고 싶습니다. 나는 돌연변이의 상태가 다음과 같은 개체를 업데이트하는 코드를 작성하는 computed 속성에 내 구성 요소로 가져올하고 단지 store.commit('increment')를 사용하여 상태 업데이트를 실행할 수있는 것처럼 보이는 문서에서

. 이것은 Vuex를 사용하는 데 필요한 최소한의 양처럼 보이지만 그 다음에 어디에서 조치가 오나요? :(혼란 최선의 방법에 어떤 도움이 작업을 수행하거나 모범 사례 주시면 감사하겠습니다!

const store = new Vuex.Store({ 
    state: { 
    count: 0 
    }, 
    mutations: { 
    increment (state) { 
     state.count++ 
    } 
    } 
}) 

내 코드

store.js 아래

import Vue from 'vue' 
import Vuex from 'vuex' 

Vue.use(Vuex); 

const db = firebase.database(); 
const auth = firebase.auth(); 

const store = new Vuex.Store({ 
    state: { 
    userInfo: {}, 
    users: {}, 
    resources: [], 
    postKey: '' 
    }, 
    mutations: { 

    // Get data from a firebase path & put in state object 

    getResources: function (state) { 
     var resourcesRef = db.ref('resources'); 
     resourcesRef.on('value', snapshot => { 
      state.resources.push(snapshot.val()); 
     }) 
    }, 
    getUsers: function (state) { 
     var usersRef = db.ref('users'); 
     usersRef.on('value', snapshot => { 
      state.users = snapshot.val(); 
     }) 
    }, 
    toggleSignIn: function (state) { 
     if (!auth.currentUser) { 
      console.log("Signing in..."); 
      var provider = new firebase.auth.GoogleAuthProvider(); 
      auth.signInWithPopup(provider).then(result => { 
      // This gives you a Google Access Token. You can use it to access the Google API. 
      var token = result.credential.accessToken; 
      // The signed-in user info. 
      var user = result.user; 
      // Set a user 
      var uid = user.uid; 
      db.ref('users/' + user.uid).set({ 
       name: user.displayName, 
       email: user.email, 
       profilePicture : user.photoURL, 
      }); 

      state.userInfo = user; 
      // ... 
      }).catch(error => { 
      // Handle Errors here. 
      var errorCode = error.code; 
      var errorMessage = error.message; 
      // The email of the user's account used. 
      var email = error.email; 
      // The firebase.auth.AuthCredential type that was used. 
      var credential = error.credential; 
      // ... 
      }); 
     } else { 
      console.log('Signing out...'); 
      auth.signOut();  
     } 
    } 
    } 
}) 

export default store 

main.js입니다

import Vue from 'vue' 
import App from './App' 
import store from './store' 

new Vue({ 
    el: '#app', 
    store, // Inject store into all child components 
    template: '<App/>', 
    components: { App } 
}) 

app.vue

<template> 
    <div id="app"> 
    <button v-on:click="toggleSignIn">Click me</button> 
    </div> 
</template> 

<script> 

import Hello from './components/Hello' 


export default { 
    name: 'app', 
    components: { 
    Hello 
    }, 
    created: function() { 
    this.$store.commit('getResources'); // Trigger state change 
    this.$store.commit('getUsers'); // Trigger state change 
    }, 
    computed: { 
    state() { 
     return this.$store.state // Get Vuex state into my component 
    } 
    }, 
    methods: { 
    toggleSignIn() { 
     this.$store.commit('toggleSignIn'); // Trigger state change 
    } 
    } 
} 

</script> 

<style> 

</style> 

답변

12

모든 AJAX는 돌연변이 대신에 동작해야합니다. 그래서 프로세스는 vuex 상태를 갱신하는 돌연변이

...에 아약스 콜백에서 데이터를 저지른 액션

... 호출하여 시작합니다.

은 참조 :

store.dispatch('fetchData') 

:

// vuex store 

state: { 
    savedData: null 
}, 
mutations: { 
    updateSavedData (state, data) { 
    state.savedData = data 
    } 
}, 
actions: { 
    fetchData ({ commit }) { 
    this.$http({ 
     url: 'some-endpoint', 
     method: 'GET' 
    }).then(function (response) { 
     commit('updateSavedData', response.data) 
    }, function() { 
     console.log('error') 
    }) 
    } 
} 
그런

당신의 아약스를 호출하는, 당신은이 작업을 수행하여 현재 작업을 호출해야합니다 : 여기

http://vuex.vuejs.org/en/actions.html은 예입니다 귀하의 경우, this.$http({...}).then(...)을 firebase ajax로 바꾸고 콜백에서 귀하의 행동을 호출하십시오.

+0

매우 정직합니다. 'fetchData'가 'saveDate'를 직접 업데이트 할 수없는 이유는 무엇입니까? 돌연변이가 중복 된 것처럼 보입니다. – Martian2049