限制 vue/vuex 反应性 [英] Restrict vue/vuex reactivity

查看:24
本文介绍了限制 vue/vuex 反应性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一些对象数组,这些对象永远不会改变.例如,这可能是从谷歌地图地点 api 接收到的搜索结果 - 每个结果都是相当复杂的对象,具有 id、标题、地址、坐标、照片和一堆其他属性和方法.

Let's assume we have some array of objects, and these objects never change. For example, that may be search results, received from google maps places api - every result is rather complex object with id, title, address, coordinates, photos and a bunch of other properties and methods.

我们想使用 vue/vuex 在地图上显示搜索结果.如果将一些新结果推送到商店,我们希望在地图上绘制它们的标记.如果某个结果被删除,我们想删除它的标记.但在内部,每个结果都不会改变.

We want to use vue/vuex to show search results on the map. If some new results are pushed to the store, we want to draw their markers on the map. If some result is deleted, we want to remove its marker. But internally every result never changes.

有什么方法可以让 vue 跟踪数组(push、splice 等),但不能更深入地跟踪它的任何元素的属性?

Is there any way to tell vue to track the array (push, splice, etc), but not to go deeper and do not track any of its element's properties?

现在我只能想象一些丑陋的数据拆分 - 将 id 数组保留在 vue 中,并在商店外按 id 单独缓存.我正在寻找更优雅的解决方案(例如knockout.js observableArray).

For now I can imagine only some ugly data split - keep the array of ids in vue and have separate cache-by-id outside of the store. I'm looking for a more elegant solution (like knockout.js observableArray).

推荐答案

您可以对这些对象使用 Object.freeze().这会带来(非常小!)性能损失,但如果您不一次添加数百或数千个对象,则应该可以忽略不计.

You can use Object.freeze() on those objects. This comes with a (really tiny!) performance hit, but it should be negligible if you don't add hundreds or thousands of objects at once.

或者,您可以冻结数组(更好的性能),这将使 Vue 跳过重新激活"其内容.

edit: Alternatively, you could freeze the array (much better performance) which will make Vue skip "reactifying" its contents.

当您需要向该数组添加对象时,请构建一个新对象来替换旧对象:

And when you need to add objects to that array, build a new one to replace the old one with:

state.searchResults = Object.freeze(state.searchResults.concat([item]))

即使对于更大的阵列,这也会很便宜.

That would be quite cheap even for bigger arrays.

这篇关于限制 vue/vuex 反应性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆