javascript - 如何使用 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)
解决方案
您必须首先将 ref 声明qrcodeVue
为类属性,而不是 inside mounted
。
只有这样它才可用并使用 ref 元素填充mounted
:
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
}
}
推荐阅读
- php - 如何使用 jquery 插入锚标记
- php - 我想根据 page_id 显示不同的内容,但是在每个页面上'echo page_id'结果都是一样的
- authentication - 使用来自不同来源的相同 cookie
- kubernetes - k8s中不同命名空间中服务的DNS名称是什么?
- android - 片段中的 Lateinit 属性尚未初始化
- c# - Dotfuscator - 无法解析 System.Reflection.BindingFlags
- python - Keras 中的计划采样
- gremlin - 在 Gremlin 中,如何在一个属性上查询两个或多个具有相同值的顶点?
- c# - 输入字符串的格式不正确。不知道如何转换输入字符串c#
- jhipster - zsh:找不到命令:jhipster Catalina mac