2016-11-03 11 views
1

ここでVuexを学び始めました。今まで私はstore.jsファイルに共有データを格納していて、すべてのモジュールにstoreをインポートしていましたが、これは迷惑になりつつあり、私は状態の変更を心配しています。Vuexで非同期呼び出しを行う

私が苦労しているのは、Vuexを使用してFirebaseからデータをインポートする方法です。私が理解していることから、アクションだけが非同期呼び出しを行うことができますが、突然変異だけが状態を更新できます。

今は私の突然変異オブジェクトから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状態を更新する責任がある突然変異

...にAJAXコールバックからのデータをコミットし、あなたの行動

...呼び出すことによって開始します。

参考:ここでhttp://vuex.vuejs.org/en/actions.html

は一例です。

// 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') 
    }) 
    } 
} 

その後、あなたのAJAXを呼び出すために、あなたがこれを行うことによって、今すぐアクションを呼び出す必要があります。

store.dispatch('fetchData') 

あなたの場合、this.$http({...}).then(...)をfirebase ajaxに置き換え、コールバックであなたの行動を呼び出してください。

+0

これは非常に正直なところです。 'fetchData'で 'saveDate'を直接更新できないのはなぜですか?突然変異は余計なようだ。 – Martian2049

関連する問題