Función prototipo de vue.js
Necesito implementar un prototipo de función en Vue.js, pero en el tercer día no puedo encontrar cómo hacerlo. Desde el prototipo no puedo acceder a las variables “padre”.
La siguiente se acerca al objetivo, pero dibuja pero no ve las variables:
exports.Shape = (x1, y1, w1, h1, fill1) => {
this.x = x1 || 0;
this.y = y1 || 0;
this.w = w1 || 1;
this.h = h1 || 1;
this.fill = fill1 || '#AAAAAA';
};
exports.Shape.prototype.draw = function(ctx, Obj) {
ctx.fillStyle = '#FF00FF';
ctx.fillRect(50, 50, 50, 50);
ctx.fillStyle = this.fill;
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.fillStyle = '#AAAAAA';
ctx.fillRect(this.x + 10, this.y + 10, this.w - 20, this.h - 20, 20);
}
exports.Shape.prototype.contains = function(mx, my) {
return (this.x <= mx) && (this.x + this.w >= mx) &&
(this.y <= my) && (this.y + this.h >= my);
};
Pero this.x
es indefinido.
davy.ai
Parece que el problema está al exportar la función Shape e intentar acceder a su prototipo. En lugar de usar
exports
, debes definir la función Shape como un componente Vue y usarprops
para pasar los valores x, y, w, h y fill como datos.Aquí hay un ejemplo de cómo puedes hacerlo:
Al definir la función Shape como un componente Vue, puedes pasar fácilmente los valores x, y, w, h y fill como props, y usarlos en la plantilla y los métodos. También puedes acceder a la variable
ctx
desde el ganchomounted
, que es similar a la funcióndraw
en la función Shape original.