在 Vue CLI 中,数据 属性 中定义的变量在与 this.VariableName 一起使用时不起作用

In Vue CLI, the defined variable inside the data property does not work, when used with this.VariableName

问题

我想在 mounted()methods: 中使用一个变量,因此在 export default {} 中的 data() 属性 中定义了它。虽然没有记录错误,但它不起作用。我该如何解决这个问题?

设置

我 运行 使用 vue 版本 3.9.3npm 版本 6.10.2。我正在使用 fabric (Javascript HTML5 canvas 库) 库,这是我的问题的一部分。

可行,但不完整的解决方案

首先,我在 mounted() 中定义了变量,它适用于 mounted()

中使用该变量调用的所有函数
var canvas = new fabric.Canvas("canvas", {
    isDrawingMode: true
});

解决方案无效

然后,因为我也想在 methods: 中使用这个变量,所以我将 var canvas 的内容放在 data() 属性 中,如下所示:

data() {
    return {
      canvas: new fabric.Canvas("canvas", { isDrawingMode: true }),
      canvasControlBar: {
        color: "#29066b"
      }
    };
  },

methods:然后我使用了这行代码:

clearCanvas() {
    this.canvas.clear();
}

两者的 console.log,mounted()this.canvas.clear() 中的 canvas.clear() 是相同的,只是 chrome 控制台显示它们略有不同。

我希望在 mounted()methods: 中使用定义为 new fabric.Canvas("canvas", { isDrawingMode: true }) 的变量。

完整代码

Whole code at Codepen.io

控制台日志

  1. 第一个日志来自 mounted()console.log(canvas.clear());
  2. 第二个日志来自 data:console.log(this.canvas.clear());

使用计算 属性 而不是数据

我没有将 var canvas 存储在 data() 中,而是将其存储在 computed: 中。因此,我使用了以下代码:

computed: {
    canvas() {
      return new fabric.Canvas("canvas", { isDrawingMode: true });
    }
  },

methods:中然后我使用了:

this.canvas.clear();

See the whole updated code on Codepen.io