使用Vuex进行异步调用

max*_*ver 3 vuex

我刚开始在这里学习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++
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

我的代码如下

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
Run Code Online (Sandbox Code Playgroud)

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 }
})
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

小智 17

所有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')
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

然后要调用你的ajax,你必须通过这样做来调用动作:

store.dispatch('fetchData')
Run Code Online (Sandbox Code Playgroud)

在您的情况下,只需this.$http({...}).then(...)使用您的firebase ajax 替换并在回调中调用您的操作.