es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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.

Tags:  , ,

Answer

  1. Avatar for 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 usar props para pasar los valores x, y, w, h y fill como datos.

    Aquí hay un ejemplo de cómo puedes hacerlo:

    <template>
      <div ref="canvas"></div>
    </template>
    
    <script>
      export default {
        props: {
          x: { type: Number, default: 0 },
          y: { type: Number, default: 0 },
          w: { type: Number, default: 1 },
          h: { type: Number, default: 1 },
          fill: { type: String, default: '#AAAAAA' }
        },
        mounted() {
          const canvas = this.$refs.canvas;
          const ctx = canvas.getContext("2d");
          this.draw(ctx);
        },
        methods: {
          draw(ctx) {
            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);
          },
          contains(mx, my) {
            return (this.x <= mx) && (this.x + this.w >= mx) &&
                (this.y <= my) && (this.y + this.h >= my);
          }
        }
      }
    </script>
    

    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 gancho mounted, que es similar a la función draw en la función Shape original.

Comments are closed.