Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict vue/vuex reactivity

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.

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.

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?

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).

like image 547
Kasheftin Avatar asked Jun 01 '17 12:06

Kasheftin


People also ask

Is Vuex state reactive?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.

What is the use of Mapstate in Vuex?

Mapping in Vuex enables you to bind any of the state's properties, like getters, mutations, actions, or state, to a computed property in a component and use data directly from the state. Although we can get the job done with this. $store.state.user.data.name , we can use a map helper to simplify it to this.

Is Vuex necessary in vue3?

Both of these could do the work of Vuex, but they aren't enough to replace Vuex completely. Let's take a look at why Vuex is is still necessary, even in Vue 3. First, Vuex offers advanced debugging capabilities that Vue 3 features does not.

What is Vuejs reactivity?

Vue's reactivity system works by deeply converting plain JavaScript objects into reactive proxies. The deep conversion can be unnecessary or sometimes unwanted when integrating with external state management systems (e.g. if an external solution also uses Proxies).


1 Answers

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.

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.

like image 144
Linus Borg Avatar answered Oct 08 '22 06:10

Linus Borg