Unlocking an HTML reference in VueJS 3 and Typescript using Vue Class Component - a step-by-step guide

I'm struggling with a challenge that involves creating a QRCode component using Vue 3 and Typescript. Here's the code snippet I've worked on:

<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>

However, I'm facing an issue where qrcodeVue seems to be referencing nothing, preventing me from accessing the canvas itself. Can anyone point out what I might be missing? Where should I place this ref() code? I also attempted using defineComponent, but encountered the same problem. Any insights would be highly appreciated.

(On a side note, I also experimented with the npm package qrcode-vue, but it appears to lack support for Vue 3)

Answer №1

To ensure the ref qrcodeVue is available and populated with the ref element in mounted, it must be declared as a class property first, rather than inside mounted.

Once you have done that, you can access it within mounted like this:

export default class QRCodeVue extends Vue {
  qrcodeVue = ref<HTMLCanvasElement | null>(null); // declare it as a class property

  mounted() {
    console.log(this.qrcodeVue);  // now you can use it
  }
}

This approach is analogous to using Vue 3's setup syntax below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Subject: Exploring the capabilities of the Vue-bootstrap-typeahead API serializer

Seeking guidance on a Vue application that utilizes vue-bootstrap-typeahead . I am puzzled by the usage of serializer in its API reference, especially when dealing with dropdown suggestions sourced from an external provider. Can someone elaborate on this c ...

javascript code to combine two JSON objects with numeric string keys and sort them in ascending order

Is there a way to combine two JSON objects with numerical string keys and arrange them in ascending order? let obj1 = { '10' : "ten" '2' : "two", "30": "thirty } let obj2 = { '4' : "four", '5' : "five", "1": "on ...

AngularJS: Organizing Controllers Horizontally Within ngRepeat

My data consists of a table with 100 rows, each representing a complex object that is an instance of a specific type. User interactions trigger operations on these objects individually, with each row having unique operations independent of the others. $sc ...

After implementing AXIOS, don't forget to refresh the static content in VUE

I'm encountering some issues with Vue.js: Currently, I have a list of elements that I'm iterating through using v-for in my script. This array is retrieved from Axios (API) in the created() lifecycle hook. Additionally, I have a static variable ...

The server will not accept the 'text/html' content type until it is terminated

I am encountering an issue with serving a simple html page through node. When I specify the content type as text/plain, the plain text of the html file loads correctly. However, when I switch it to "content-type" : "text/html", the browser tab keeps loadi ...

Angular-cli is encountering an Uncaught ReferenceError with global variables in Karma

My Angular 4.0 project was created using angular-cli 1.0. I am utilizing global variables such as API endpoints that change based on the environment during deployment through Octopus Deploy. global-tokens.js var apis = { foo: 'http://foobar.foo ...

The dropdown menu is not able to retrieve information from the secondary database

I have been encountering multiple challenges while working on a web-based dynamic form that I am developing. My current major issue is with populating the second #bodytype dropdown based on the selection made in the first, #bodyman, dropdown. Subsequently ...

Are you making alterations to the URL?

Is there a way to change the displayed URL on a webpage to show "bananas" instead of "http://example.com/" after the page has loaded? ...

Error rotating the camera in Three.js

I can't figure out why Firebug keeps throwing an error that says "THREE is not defined" for my var camera. It's confusing because I clearly see the THREE declaration on the right side of the equals sign. init(); animate(); ...

Creating a Vue Canvas with Endless Grid Dots and a Dynamic Panning Feature

I'm currently focused on integrating a panning system into the canvas of my Vue application. Although I have successfully implemented the panning system, I am encountering difficulties in efficiently rendering an infinite grid of dots. Below is the c ...

"Two distinct routes in Angular, but keeping the same menu item highlighted as

In my app-component.ts, I have a menu structured like this: <ul> <li> <a href="#" routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a> </li> <li> <a href="#" route ...

The link.url in my code is consistently changing, while the pathName remains static

My code is experiencing an issue where link.url is changing but pathName is not. I am trying to implement an animation transition on my website, but it is not working correctly because the pathName and link.url do not match. "use client" import ...

Implementing dynamic data filtering in Vue.js is a valuable feature that

I'm working on a Vuejs project where I need to filter out only the questions with reviewed:true and get the count of them. However, I'm encountering an error while using the code below: TypeError: question.reviewed.includes is not a function. Can ...

Assistance with Troubleshooting a Complicated JavaScript/TypeScript Software

As someone new to the world of Javascript and Typescript, I am looking to gain a deeper understanding of how a specific large application runs through its steps. Can anyone suggest a debugger or other helpful tool for this task? ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

The prop type for `rows` is invalid in `ForwardRef(DataGrid)`. It was supplied as an object instead of the expected array

Hello there! I'm puzzled as to why my grid table isn't displaying data even though I can confirm that I am receiving data from the API response. I'm wondering what might be wrong with my code. Below is my current code along with the returned ...

Is the term "filter" considered a reserved keyword in Angular, Javascript, or ASP.Net MVC?

When using angularJS to call an ASP.Net MVC controller from a service, I encountered an issue with one of the parameters: $http({ method: "get", url: "ControllerMethod", params: { param1: param1Value, pageNumber: pageNumber, ...

Sending a form with a value that cannot be edited: what's the best way?

<form action="/upload" method="POST" enctype="multipart/form-data"> <fieldset> <span>Event name</span> <input name = "name" type="text" class="form-control" value="<%= `${event.name}` %>" readonly> ...

The chart JS label callback requires a specified type declaration

Currently, I am in the process of updating an old Angular platform to a newer version. One requirement is that everything must have its type declaration. I encountered a problem with the label callback showing this error: The error message reads: "Type &a ...

Adjust the opacity of a div as you scroll using jQuery

Check out my code snippet: http://jsfiddle.net/spadez/Fq5K4/ I am looking to create a cool effect where the image in the top section gradually turns black as the user continues scrolling down the page, until it is completely black. This example showcases ...