I am facing a challenge with setting the focus on a specific text input element within a modal dialog. I have tried various methods but none seem to achieve the desired outcome. Here is what I have attempted:
Attempt 1: Using autofocus attribute.
<input placeholder="Enter search text" type="text" autofocus class="form-control" v-model="searchterm"/>
The input does not focus, and there are no errors...
Attempt 2: Implementing a custom directive (v-focus) on the input element.
<input placeholder="Enter search text" type="text" v-focus class="form-control" v-model="searchterm"/>
<script lang="ts">
import { defineComponent, PropType } from "@vue/runtime-core";
export default defineComponent({
name: "Crops-view",
setup() {
},
directives: {
focus: {
mounted: (el) => {
el.focus();
console.log("focus set");
},
},
props: { ... ...},
});
</script>
This method triggers the routine at page load instead of when the modal dialog opens. It won't work for multiple dialogs with individual initial focus points.
Attempt 3: Utilizing watch to trigger function upon change in dialog visibility.
<div
class="modal fade m-3 p-3 justify-content-center"
id="crops-modal"
data-bs-backdrop="static"
v-show="showCropsModal"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="title text-center">Crops</div>
</div>
<div class="row m-2">
<input
placeholder="Enter search text"
type="text"
class="form-control"
v-model="searchterm"
/>
</div>
</div>
</div>
</div>
</div>
<script lang="ts">
import { defineComponent, PropType, ref } from "@vue/runtime-core";
export default defineComponent({
name: "Crops-view",
setup() {
const showCropsModal = true;
const cropsearchinput = ref<HTMLInputElement>();
return { showCropsModal, cropsearchinput};
},
watch: {
showCropsModal(value) {
if (value) {
(cropsearchinput.value as HTMLElement).focus();
}
},
},
props: { ... ...},
});
</script>
This code does not compile and throws a lint error stating 'cropsearchinput' is not defined.
I have explored various options including directives, methods, watches, v-focus, and autofocus.