5

ここで Vuex を学び始めたところです。今までは共有データをstore.jsファイルに保存storeしてモジュールごとにインポートしていたのですが、これが面倒くさくて状態の変化が気になります。

私が苦労しているのは、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>
4

1 に答える 1

20

すべての AJAX は、ミューテーションではなくアクションに移行する必要があります。したがって、プロセスはアクションを呼び出すことから始まります

...データを ajax コールバックからミューテーションにコミットします

...これは、vuex の状態を更新する責任があります。

参照: 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 に置き換えて、コールバックでアクションを呼び出すだけです。

于 2016-11-23T15:58:51.707 に答える