Adding an HTML element to a class component in Vue 3 using Class Components and Typescript through a click event

In the context of Vue3 with typescript and vue-class-component, I am attempting to dynamically append a created div to a specific div element within the template tag when an input template Element is in focus.

I have experimented with two approaches:

1. Initially, I tried selecting the template div element by its id and appending the dynamically created div to it upon focusing on the input element:

<template>
  <div id="testId" ref="errorDiv">
    <input type="text" @focusin="handleFocusIn"/>
  </div>
</template>

<script lang="ts">
  import { Vue } from 'vue-class-component';

  export default class HelloWorld extends Vue {

    public handleFocusIn = (): void => {
      
      this.appendDivById(); // <----- issue arises when using component multiple times on the same page
      
    }

    private appendDivById() : void {
      let errorDivRef = document.getElementById('testId') as HTMLDivElement

      var div = document.createElement("div") as HTMLDivElement;
      div.innerHTML = "Hello World";

      errorDivRef.append(div);
    }

  }
</script>

This method works initially, but fails when the component is used multiple times on the same page due to all elements having the same id resulting in all dynamic divs being appended to the first div.

2. Alternatively, I attempted to select the template div element by its reference and append the new div to it:

<template>
  <div id="testId" ref="errorDiv">
    <input type="text" @focusin="handleFocusIn"/>
  </div>
</template>

<script lang="ts">
  import { Vue } from 'vue-class-component';

  export default class HelloWorld extends Vue {

    declare $refs: {
      errorDiv: HTMLDivElement;
    };

    public handleFocusIn = (): void => {
      
      this.appendDivByRef(); // <----- encountering issues as $refs.errorDiv always undefined
      
    }

    public mounted() { 
      var div = document.createElement("div") as HTMLDivElement;
      div.innerHTML = "Hello World";

      this.$refs.errorDiv.append(div); // <----- $refs.errorDiv not undefined
    }

    private appendDivByRef() : void {
      var div = document.createElement("div") as HTMLDivElement;
      div.innerHTML = "Hello World";

      this.$refs.errorDiv.append(div); // <----- experiencing $refs.errorDiv always undefined
    }

  }
</script>

The second approach fails as the reference is consistently undefined. It seems that references can only be accessed within the mounted function, which occurs at the wrong time for this purpose.

Using v-for for dynamic lists is not applicable in this scenario as I aim to append a singular element.

Am I on the right path or completely off-base with my approach?

Answer №1

In my opinion, one of the most effective ways to implement functionality like this is by utilizing the modern composition api and moving away from traditional class components.

An example implementation could look something like this:

<template>
  <div id="testId" ref="errorDiv">
    <input type="text" @focusin="handleFocusIn"/>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  
  const errorDiv = ref<HTMLDivElement>();
  
  function handleFocusIn(): void {
    var div = document.createElement("div") as HTMLDivElement;
    div.innerHTML = "Hello World";
    errorDiv.value?.append(div);
  }
</script>

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

Prevent coverage tracking for files or paths enclosed in square brackets in jest

I am trying to exclude a specific file from test coverage in Jest by modifying the collectCoverageFrom array. The file name contains square brackets, and I have added an entry with a negation for this file. collectCoverageFrom: [ './src/**/*.{js ...

What is the reason behind receiving the error message "`Foo` only represents a type, but is being treated as a value here" when using `instanceof` in TypeScript?

As the creator of this code interface Foo { abcdef: number; } let x: Foo | string; if (x instanceof Foo) { // ... } Upon running this code, I encountered an error in TypeScript: 'Foo' is recognized only as a type and cannot be used a ...

The value is not being found in my form, and the slide-toggle is consistently checked

I am encountering an issue with my forms. On the web, all my slide-toggle options are pre-checked as shown in the image provided. I suspect that the problem lies within the patchFor(){} function. Could someone please review my code for me? I have attempte ...

Discovering the class type in TypeScript

In my TypeScript coding journey, I encountered a challenge in detecting a specific Class type. Despite its seeming simplicity, I found a lack of straightforward documentation on how to accomplish this task. Here is an example that illustrates the issue: Cl ...

Issue encountered in Loopback 4: Error with @repository dependency injection (TypeError: Undefined property 'findOne')

As I set up Bearer Token authentication for my Loopback 4 application, I referenced this implementation guide: https://github.com/strongloop/loopback-next/tree/master/packages/authentication. Within my src/providers/auth-strategy.provider.ts file, I encou ...

Tips for converting module.exports object structure from JavaScript to TypeScript

I am currently in the process of converting my node.js app to TypeScript, and I have come across a number of index.js files with the following setup: module.exports = { query: require('./query'), mutation: require('./mutation') } T ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

Error in Visual Studio when declaring Angular 6 components

Recently, I completed the upgrade of my project from Angular 4 to Angular 6. However, upon doing so, I encountered a compiler error in Visual Studio related to my Component declarations. Specifically, the basic declaration below is being highlighted in red ...

Participating in consolidated data

I need to merge data from my trainings-table with my users-table. The structure of the data is as follows: - users - key1 - name - trainingIds - t_key1 - t_key3 - trainings - t_key1 - name - description - t_k ...

Extract data from a string and assign it to a variable representing an

I have a custom function that parses a string and converts numbers and boolean values to their appropriate JavaScript primitives. This function is specifically designed for working with query parameters: const parseQueryParams = (searchString: string) => ...

The Updating Issue: Angular 2 Table Fails to Reflect Value Changes

I have initialized a table with user details using the ngOnInit() method. When I click on the "create user" button, it opens a form to add a new user to the database. However, the table does not update automatically with the new user's information. H ...

Using TypeScript to Import Modules without Default Exports (CommonJS)

Can a module that is defined without a default export be imported using import module from 'module'; and then compiled to commonjs? An answer on Stack Overflow suggests that it might be possible with the use of the --allowSyntheticDefaultImports ...

Using Angular: Binding Angular variables to HTML for display

I have a component with a ts file that contains HTML content as a variable. Let's say para1= <a href="www.google.com">sitename</a> more content I want to bind this paragraph in HTML as if it were actual HTML tags. sitename What is the ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

"Trouble arises when trying to import a Vue component into a TypeScript file

Within my Vue project, I have created a new TypeScript file named Validation.ts: import Vue from 'vue'; import BaseInput from '@/components/base/BaseInput.vue'; class ValidationService extends Vue { validateFields(fields: BaseInput[] ...

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...