【问题标题】:Vue mutation change instance (MyArray to Array)Vue 突变变更实例(MyArray 到 Array)
【发布时间】:2020-04-05 11:21:01
【问题描述】:

我正在用我的类 MyArray 扩展内置 Array 当我尝试将 MyArr 存储到 Vuex 时,我丢失了实例,并获得了 bultIn Array

怎么了?

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?
  }
}

【问题讨论】:

    标签: arrays vue.js vuex


    【解决方案1】:

    要使数组具有响应性,Vue 需要使用自己的版本修补各种方法,例如 pushpop。在触发反应系统时,它们的工作方式与原件相同。

    为了快速实现这个补丁,Vue 将 Array 的原型切换到它自己的扩展版本。见:

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

    具体情况因浏览器支持而异。

    instanceof 运算符根据原型链确定其值。一旦 Vue 进行了切换,您的数组将不再在其原型链中包含 MyArray

    【讨论】:

    • 问题是关于为什么 Vue 切换数组。与反应性、流行和推送无关
    • @user1272025 我的回答解释了为什么 Vue 会切换数组。
    猜你喜欢
    • 2018-10-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2018-02-04
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多