Javascript 如何使用Vue类组件访问VueJS 3中的HTML引用和Typescript?
我遇到了以下问题:我使用Vue 3和Typescript创建了一个QRCode组件,代码如下:Javascript 如何使用Vue类组件访问VueJS 3中的HTML引用和Typescript?,javascript,typescript,vue.js,vuejs3,vue-class-components,Javascript,Typescript,Vue.js,Vuejs3,Vue Class Components,我遇到了以下问题:我使用Vue 3和Typescript创建了一个QRCode组件,代码如下: <template> <canvas ref="qrcodeVue"> </canvas> </template> <script lang="ts"> import QRCode from "qrcode"; import { Vue, Options } from &quo
<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>
从“QRCode”导入QRCode;
从“Vue类组件”导入{Vue,Options};
从“vue”导入{ref};
@选择权({
道具:{
价值:{
类型:字符串,
必填项:true
},
尺寸:{
类型:[数字,字符串],
验证程序:(s:[number | string])=>isNaN(number))!==true
},
级别:{
类型:字符串,
验证器:(l:string)=>[“l”、“Q”、“M”、“H”]。indexOf(l)>-1
},
背景:字符串,
前景:字符串
}
})
导出默认类QRCodeVue扩展Vue{
value=“”;
大小:数字|字符串=100;
级别:“L”|“Q”|“M”|“H”=“L”;
背景=“#ffffff”;
前台=“#0000ff”;
安装的(){
const_size=数量(此.size);
const scale=window.devicePixelRatio | | 1;
常量qrcodeVue=ref(空);
QRCode.toCanvas(qrcodeVue,this.value{
比例:比例,
宽度:_尺寸,
颜色:{深色:this.foreground,浅色:this.background},
errorCorrectionLevel:此.level
});
}
}
但是qrcodeVue
总是指什么都没有,我从来没有访问过画布本身。我错过了什么?我应该把这个ref()
code放在哪里?我还尝试了defineComponent
,得到了相同的结果。谢谢你提供任何线索
(顺便说一句,我还尝试使用npm
qrcode vue
包,但它似乎不支持vue 3)您必须首先将refqrcodeVue
声明为类属性,而不是在装入的
中
只有到那时,它才可用,并在mounted
中填充ref元素:
导出默认类QRCodeVue扩展Vue{
qrcodeVue=ref(null);//未安装在内部
安装的(){
console.log(this.qrcodeVue);//现在它可用了
}
}
这相当于以下Vue 3设置
语法:
setup(){
常量qrcodeVue=ref(空);
未安装(()=>{
console.log(qrcodeVue.value);
})
返回{
qrcodeVue
}
}
我认为您可能缺少qrcodeVue的.value
部分来访问画布元素QRCode.toCanvas(qrcodeVue.value,this.value,…)
。谢谢Ibrahim。见下面丹的答案,了解真实情况。