canvas、切换组件的 vueJS 生命周期

vueJS life cycle with canvas, switching components

我在显示包含具有不同行为的 canvas 的 vue 组件时遇到了一些问题。

我希望能够 "switch component" 使用 v-if 并传递不同的属性。

我做了一个小例子,代码如下:

现在发生的事情是,当我切换到 'blue' 时,'red' 仍然是 "living",所以当我绘制颜色时,颜色仍然是 'red',尽管我可以看到dom 正在更改并切换到 'canvas2'

--- 组件------

<template>
        <div class="container-fluid">

        <canvas style="border: 1px solid black;" width="300px" height="150px" :id="'canvas'+canvasKey"></canvas>

        </div>
        </template>

    export default {
        data: function() {
            return {
            }
        },
        mounted: function() {
            this.draw_canvas()
        },
        created: function() {
        },
        watch: {},
        props: ['canvasKey'],
        computed: {},
        methods: {
            draw_canvas: function() {
                var app = this
                var c = document.getElementById("canvas"+this.canvasKey)
                var ctx = c.getContext("2d");

                if(this.canvasKey == 1) {
                    var color = 'red'
                } else if(this.canvasKey == 2) {
                    var color = 'blue'
                }

                var mousePos = function(mouseEv) {
                    let offset = $("#canvas"+app.canvasKey).offset()
                    let pos = {
                        x: mouseEv.pageX - offset.left,
                        y: mouseEv.pageY - offset.top,
                    }
                    return pos
                }

                $('#canvas'+this.canvasKey).on('mousemove' , function(ev) {
                    var pos = mousePos(ev)
                    ctx.beginPath()
                    ctx.arc(pos.x, pos.y, 10, 0, 2 * Math.PI)
                    ctx.fillStyle = color
                    ctx.fill()
                })
            }
        }
    }

---创建组件---

<canvas-test v-if="color == 'red'"  canvasKey="1"></canvastest>
<canvas-test v-if="color == 'blue'" canvasKey="2"></canvas-test>

我希望我把我的问题说清楚了,非常感谢你的帮助,提前谢谢你

您在 v-if 语句中使用了 non-reactive 变量。这不受支持,最终效果是 v-if 评估不会改变,即使 color 改变了,所以它总是呈现相同的组件。

在 parent 组件中切换到使用颜色 data 属性,例如,使用 v-modelv-bind:value 来使用它(如指南中的 Using-v-model-on-Components 中有描述)。 在 parent:

<template>
  ...
    <canvas-test v-if="color == 'red'" v-model="color"  canvasKey="1"></canvastest>
    <canvas-test v-if="color == 'blue'" v-model="color" canvasKey="2"></canvas-test>
  ...
</template>
<script>
...
export default {
  data () {
    ...
    color: 'red',
    ...
  }
  ...
  components: {
    CanvasTest
  }
  ...
}
</script>

在 canvas 组件中:

<script>
...
export default {
  ...
  props: ['value'],  // the color is in 'value'
  ...
}
</script>

如果您只想拥有多个具有不同属性的组件,只需使用 props.

定义它们的属性