如何使用Vue类组件访问VueJS 3和Typescript中的HTML引用



我遇到了以下问题:我使用Vue 3和Typescript创建了一个QRCode组件,代码如下:

<template>
<canvas ref="qrcodeVue"> </canvas>
</template>
<script lang="ts">
import QRCode from "qrcode";
import { Vue, Options } from "vue-class-component";
import { ref } from "vue";
@Options({
props: {
value: {
type: String,
required: true
},
size: {
type: [Number, String],
validator: (s: [number | string]) => isNaN(Number(s)) !== true
},
level: {
type: String,
validator: (l: string) => ["L", "Q", "M", "H"].indexOf(l) > -1
},
background: String,
foreground: String
}
})
export default class QRCodeVue extends Vue {
value = "";
size: number | string = 100;
level: "L" | "Q" | "M" | "H" = "L";
background = "#ffffff";
foreground = "#0000ff";
mounted() {
const _size = Number(this.size);
const scale = window.devicePixelRatio || 1;
const qrcodeVue = ref<HTMLCanvasElement | null>(null);
QRCode.toCanvas(qrcodeVue, this.value, {
scale: scale,
width: _size,
color: { dark: this.foreground, light: this.background },
errorCorrectionLevel: this.level
});
}
}
</script>

但是qrcodeVue总是指什么都没有,我从来没有访问过画布本身。我错过了什么?我应该把这个ref()代码放在哪里?我也尝试了defineComponent,得到了同样的结果。谢谢你提供任何线索。

(顺便说一句,我也尝试过使用npmqrcode-vue包,但它似乎不支持Vue 3(

您必须首先将refqrcodeVue声明为类属性,而不是在mounted内部。

只有到那时,它才可用,并在mounted:中填充ref元素

export default class QRCodeVue extends Vue {
qrcodeVue = ref<HTMLCanvasElement | null>(null); // not inside mounted
mounted() {
console.log(this.qrcodeVue);  // now it's available
}
}

这相当于以下Vue 3setup语法:

setup() {
const qrcodeVue = ref(null);
onMounted(() => {
console.log(qrcodeVue.value);
})
return {
qrcodeVue
}
}

最新更新