I have a Vue.js 2 component where one of the data members should be an array of a custom class (Vector) that extends from Array. However, when I assign the array to the data member, the array's items are no longer Vectors, but plain Array's.
Here is an example: https://codesandbox.io/embed/nervous-tu-7en2q?fontsize=14&hidenavigation=1&theme=dark
Main parts:
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),
]
Component:
<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>
If you look at the console output, you will see the square is now an array of two arrays in stead of an array of two Vectors:
(2) [Array(2), Array(2)]
Questions:
I'm not exactly sure what's the issue but I tried rewriting almost the same using a different pattern, could you check if this solves your problem? If not hopefully a different approach would get you more clues.
Basically for what I see you will get a 2 numbers array everytime you create a vector, are you expecting it to be of other type?
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>