ここで 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>