이제 Vuex를 배우기 시작했습니다. 지금까지 나는 store.js
파일에 공유 데이터를 저장하고 모든 모듈에 store
을 가져오고 있지만 이것은 성가 시게되고 있으며 상태를 변경하는 것에 대해 걱정하고 있습니다.Vuex로 비동기 호출하기
저는 Vuex를 사용하여 Firebase에서 데이터를 가져 오는 방법에 대해 고심하고 있습니다. 내가 알고있는 것에서 만 액션이 비동기 호출을 할 수 있지만 변형 만이 상태를 업데이트 할 수 있습니까?
지금은 내 mutations 객체에서 firebase를 호출하고 있습니다. 정상적으로 작동하는 것으로 보입니다. 솔직히 모든 컨텍스트, 커밋, 디스패치 등은 약간 과부하 상태입니다. Vuex를 생산적으로 사용하는 데 필요한 최소량 만 사용하고 싶습니다. 나는 돌연변이의 상태가 다음과 같은 개체를 업데이트하는 코드를 작성하는 computed
속성에 내 구성 요소로 가져올하고 단지 store.commit('increment')
를 사용하여 상태 업데이트를 실행할 수있는 것처럼 보이는 문서에서
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>
매우 정직합니다. 'fetchData'가 'saveDate'를 직접 업데이트 할 수없는 이유는 무엇입니까? 돌연변이가 중복 된 것처럼 보입니다. – Martian2049