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

查看:101
本文介绍了限制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跟踪阵列(推,拼接等),但不要更深入,不要跟踪它的任何元素的属性?

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?

现在我可以想象只有一些丑陋的数据拆分 - 将ids数组保留在vue中,并在商店外部具有单独的cache-by-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天全站免登陆