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?