【问题标题】:Vue's reactivity changes data typeVue 的响应式更改数据类型
【发布时间】:2021-12-07 16:31:12
【问题描述】:

我有一个 Vue.js 2 组件,其中一个数据成员应该是从 Array 扩展的自定义类 (Vector) 的数组。但是,当我将数组分配给数据成员时,数组的项不再是向量,而是普通数组。

这里是一个例子:https://codesandbox.io/embed/nervous-tu-7en2q?fontsize=14&hidenavigation=1&theme=dark

主要部分:

vector.js

export default class Vector extends Array {
  /** Creat a vector from all arguments. */
  constructor(...args) { ... }

  get x() {
    return this[0];
  }
  get y() {
    return this[1];
  }
};

export const square = [
  new Vector(0, 0),
  new Vector(1, 1),
]

组件:

<template>
  <div id="app">
    {{ title }}
    ({{ square[0][0] }}, {{ square[0][1] }})
    ({{ square[1].x }}, {{ square[1].y }})
  </div>
</template>

<script>
import { square } from './vector.js';

export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      square,
      title: 'hello'
    }
  },
  mounted() {
    console.log(this.square)
  }
};
</script>

如果您查看控制台输出,您会看到正方形现在是两个数组的数组,而不是两个向量的数组:

(2) [数组(2),数组(2)]

问题:

  1. 这应该发生吗?如果是,为什么?
  2. 可以预防吗?一种选择是通过将其移出数据部分来防止它具有反应性,但这当然会扼杀良好的反应性部分。

【问题讨论】:

  • 这是与 vue2 相关的主要问题之一。但是,这应该通过 vue3 或组合 api 来解决。基于代理,反应机制在后者中的工作方式不同。哪个应该保留向量的构造函数而不是破坏它。见:github.com/vuejs/composition-api

标签: javascript vue.js vuejs2


【解决方案1】:

我不确定是什么问题,但我尝试使用不同的模式重写几乎相同的内容,您能否检查这是否解决了您的问题?如果不是希望另一种方法可以为您提供更多线索。

基本上,就我所见,您每次创建vector 时都会得到一个2 numbers array,您是否希望它是其他类型的?

这是我的重写:

vector.js

const vector = (x, y) => ({
    values: [x, y],
    setX(newValue) {
      this.values[0] = newValue
      return this
    },
    setY(newValue) {
      this.values[1] = newValue
      return this
    },
    getX() {
      return this.values[0]
    },
    getY() {
      return this.values[1]
    }
})

export default vector

export const square = [vector(0, 0).values, vector(1,1).values];
<script>
import vector, { square } from "./vector.js";

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      square,
      vector: vector(1, 2).values,
      title: "Corners",
    };
  },
  mounted() {
    console.log('square', this.square);
    console.log('vector', this.vector);
  },
};
</script>

【讨论】:

  • 抱歉回复晚了。您现在通过将 .values 传递给 square 和 this.vector 来自己转换为数组。所以你仍然不能将它用作 this.square[0].getX() 中的向量。我猜@RonaldT 的评论清楚地表明你无法阻止这种“上扬”。
猜你喜欢
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2018-10-11
  • 2020-10-18
  • 2011-06-12
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多