我喜欢 Firebase 等实时数据库的一点是它们的推送功能。例如,vuefire 使拥有 self 更新对象变得非常简单,而无需串起数百个套接字监听器和回调。
这是一个例子:
data(){
return {
books: []
}
},
created(){
axios.get('/books', (books) => {
this.books = books
})
}
为了向其中添加数据库 react 性,我至少需要 3 个事件“book-created”、“book-updated”、“book-removed”。
Pusher.on('book-created', (book) {
this.books.push(book)
})
Pusher.on('book-updated', (book) {
let b = _.find(this.books, {id: book.id})
if(b){
_.extend(b, book)
}
})
etc..
当你有很多模型和很多 View 时,它会变得很毛茸茸,有些 View 有不同的书集,所以我不能只有一个标准的书 vuex 变量。有没有一种明智/快速的方法来解决这个问题?
我当然可以抽象化后端发送的事件,这样我所有的模型都会自动推送事件。但前端是我感到困惑的地方。
最佳答案
我以前从未使用过 pusher,我不知道你指的是什么“不同的书集”,但我想我可以给你一些起点,让你的代码看起来更优雅.
我建议的第一件事; 不要试图重新发明轮子,使用component mixins .只需创建一个 mixin,就像您通常使用后端一样,使其与一些动态选项(您可以在组件的 data()
中设置)一起使用,并将其导入到您需要相同功能的每个组件上, 有不同的选择。
Example (你需要相应地调整它)
// Create an ES6 module and export this function, or the whole mixin
// (in that case export the mixin instead)
const initPusher = function ({pusher, collection, key, events}, component) {
collection = component[collection]
pusher.on(events.created, (record) => {
collection.push(record)
})
pusher.on(events.updated, (record) => {
let r = _.find(collection, {[key]: record[key]})
if(r){
_.extend(r, record)
}
})
}
const PusherMixin = {
methods: {
// You can add some common methods for all your
// components making use of this mixin
},
created () {
initPusher(Object.assign({}, {
pusher: Pusher,
collection: 'collection',
key: 'id',
events: {
created: 'book-created',
updated: 'book-updated'
}
}, this.pusherOptions), this)
}
}
new Vue({
el: "#app",
mixins: [PusherMixin],
data () {
return {
books: [],
pusherOptions: {
collection: 'books',
key: 'id',
events: {
created: 'book-created',
updated: 'book-updated'
}
}
}
}
})
我的第二个建议是使用一些自定义方法和钩子(Hook)来触发事件和 XHRequests好的 mixin 与此完全相反。
如果你想更深入,你可能想看看 RxJS 和 observables。您可以使用 Pusher 在其之上构建一些东西,以获得类似于 Firebase 实时对象的东西。
关于javascript - 是否有一种标准/优雅的方法可以在没有 Firebase 的情况下实现类似 Firebase 的 react 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49611680/