Vuex를 사용한 비동기 콜 발신
Vuex는 이제 막 배우기 시작했어요.지금까지 저는 공유 데이터를store.js
파일 및 Importstore
모든 모듈에서 사용되는데 이게 귀찮아져서 상태가 변질될까 봐 걱정이에요.
문제는 Vuex를 사용하여 FireBase에서 데이터를 Import하는 방법입니다.비동기 호출을 할 수 있는 것은 액션뿐이지만 상태를 갱신할 수 있는 것은 돌연변이뿐인 것으로 알고 있습니다.
지금 내 돌연변이 물체에서 파이어베이스로 전화를 걸었는데 잘 작동하고 있는 것 같아.솔직히 모든 컨텍스트, 커밋, 디스패치 등이 다소 과부하인 것 같습니다.생산성을 높이기 위해 필요한 최소한의 Vuex만 사용할 수 있으면 됩니다.
문서에서는 다음과 같이 돌연변이 오브젝트의 상태를 갱신하는 코드를 작성하고, 그것을 내 컴포넌트로 Import할 수 있는 것처럼 보입니다.computed
를 사용하여 상태 업데이트를 트리거합니다.store.commit('increment')
Vuex를 사용하기 위해 필요한 최소한의 양이라고 생각됩니다만, 그럼 액션은 어떻게 되는 것입니까?혼란스러움:(이 방법 또는 베스트 프랙티스에 대한 어떤 도움도 받을 수 있습니다!
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
내 코드는 다음과 같습니다.
store.displaces를 설정합니다.
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.discloss.main.discloss.
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>
모든 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(...)
파이어베이스 에이잭스를 호출하고 콜백에서 조치를 취합니다.
언급URL : https://stackoverflow.com/questions/40403657/making-async-calls-with-vuex
'source' 카테고리의 다른 글
glibc의 stren은 왜 이렇게 복잡해야 빨리 실행할 수 있나요? (0) | 2022.09.01 |
---|---|
치명적인 오류: mpi.h: 해당 파일 또는 디렉토리 #이(가) 없습니다. (0) | 2022.09.01 |
전체 새로 고침 후 항목이 표시되지 않는 Vuetify v-select (0) | 2022.09.01 |
외부 테마 파일에 의해 생성되는 Dart SAS 경고 비활성화 (0) | 2022.09.01 |
어레이 초기화와 동등한 Array List 초기화 (0) | 2022.09.01 |