Precondition: Vue3 + typescript + vue-class-component Im trying to append a dynamic created div to a div element inside of the template tag on focusin on an input template Element.
I tried two ways to do that:
1. I tried to get the template div element by its id and append the dynamic created div to it on focusin of 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(); // <----- not working when using this component multiple times on samae 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>
That seems to work but when you are using that component multiple times on the same page all elements have the same Id and every dynamic created div will be appended to the first div.
2. I tried to get the template div element by its reference and append the dynamic created 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;
};
// errorDiv = ref<HTMLDivElement | null>(null); // <----- errorDiv.value is always null even in mounted
public handleFocusIn = (): void => {
this.appendDivByRef(); // <----- not working $refs.errorDiv always undefined
}
public mounted() { // <----- working but wrong time
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); // <----- not working $refs.errorDiv always undefined
}
}
</script>
This is not working because the reference is always undefined. If I have understood correctly, you can only access a reference in the mounted function, but this is the wrong time.
The Option using v-for for dynamic lists is not the right in this case because I want to append exact one element.
Am I on the right track or is this approch completly wrong?