user1272025
user1272025

Reputation: 21

Vue mutation change instance (MyArray to Array)

I'm extending builtIn Array with my class MyArray When i try to store MyArr to Vuex, I loose instance, and get bultIn Array

What's wrong?

class MyArray extends Array{/*some methods*/}

const state = {
  arr: new ModuleOperationArray(),
}

const mutations = {
  setArr: (state) => {
   console.log(state.arr instanceof MyArray); //false -- WHY?

   let arr = new MyArray();
   console.log(arr instanceof MyArray); //true -- expectedly

   state.arr = arr;
   console.log(state.arr instanceof MyArray); //false -- WHY?
  }
}

Upvotes: 1

Views: 53

Answers (1)

skirtle
skirtle

Reputation: 29092

To make arrays reactive Vue needs to patch various methods such as push and pop with its own versions. These work just the same as the originals while triggering the reactivity system.

To achieve this patching quickly Vue switches out the prototype of the Array to its own extended version. See:

https://github.com/vuejs/vue/blob/9fbd416635eb3d7b32cd73b7c29f8377003c4dc8/src/core/observer/index.js#L49

The specifics vary depending on browser support.

The instanceof operator determines its value based on the prototype chain. Once Vue has made the switch your array will no longer have MyArray in its prototype chain.

Upvotes: 1

Related Questions