Restrict vue/vuex reactivity

Viewed 9785

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

4 Answers

I created a fork out of vue called vue-for-babylonians to restrict reactivity and even permit some object properties to be reactive. Check it out here.

With it, you can tell Vue to not make any objects which are stored in vue or vuex from being reactive. You can also tell Vue to make certain subset of object properties reactive. You’ll find performance improves substantially and you enjoy the convenience of storing and passing large objects as you would normally in vue/vuex.

You can use shallowRef to achieve this.

First import it:

import {shallowRef} from 'vue';

In your mutations you can have a mutation like this:

mutations: {
    setMyObject(state, payload) {
      state.myObject = shallowRef(payload.value);
    },
}

This will track replacing the object, but not changes to the objects properties.

For completeness here is the documentation to shallowRef:

https://v3.vuejs.org/api/refs-api.html#shallowref

Related