我正在尝试在我正在构建的应用程序中实现 Vuex,以了解有关 Vue.js 的更多信息。这个想法非常简单:检索用户信息和项目列表(所有内容都存储在 Firebase 上)。
我了解了 Vuex 的想法,但我能找到的教程仅依赖于本地存储在
store
中的数据。当 store
中的数据必须与外部数据库保持同步时,我无法理解它是如何工作的。
我完全错过了什么吗?或者也许 Vuex 不是最好的解决方案?
如果您希望“(Vue.js)存储中的数据与外部(Firestore)数据库保持同步”,您可以执行以下操作,利用“附加侦听器”的
onSnapshot()
方法对于 QuerySnapshot
事件”。
假设您的 Firestore 数据库中有一个
cities
集合,该集合的每个文档都有一个字段 name
,其中包含城市名称。
首先,在
firebaseConfig.js
文件中声明 Firebase 配置:
firebaseConfig.js
import firebase from 'firebase/app';
import 'firebase/firestore';
// firebase init goes here
const config = {
apiKey: 'xxxxxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxx.firebaseapp.com',
databaseURL: 'xxxxxxxxxxxxxxxxxx',
projectId: 'xxxxxxxxxxxxxxxxxx'
};
firebase.initializeApp(config);
const db = firebase.firestore();
export { db };
然后按如下方式设置您的 Vuex 商店:
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
cities: []
},
mutations: {
SET_CITIES(state, val) {
state.cities = val;
}
},
actions: {
//You may add here an action that would commit the SET_CITIES mutation
}
});
然后,修改
main.js
文件如下:
main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
const fb = require('./firebaseConfig.js');
Vue.config.productionTip = false;
new Vue({
router,
store,
beforeCreate() {
fb.db.collection('cities').onSnapshot(querySnapshot => {
var c = [];
querySnapshot.forEach(doc => {
c.push({
id: doc.id,
name: doc.data().name
});
});
store.commit('SET_CITIES', c);
});
},
render: h => h(App)
}).$mount('#app');
一切都准备好了!只需尝试在组件中获取城市数组,如下所示:
HelloWorld.vue
<template>
<div>
<ul>
<li v-for="c in cities" v-bind:key="c.id">{{ c.name }}</li>
</ul>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
name: "HelloWorld",
computed: {
...mapState(["cities"])
}
};
</script>
并尝试添加、删除或修改数据库中的记录。