I have created a component called Input
. All the attributes that are passed to this Input
component are inherited successfully, but the ref
attribute is always omitted for some reason.
I need the ref
attribute to set focus on the element, after the validation fails.
Some.vue
<template>
...
<Input
type="number"
name="mobile"
ref="mobileRef"
v-model="this.form.mobile"
:
:error="errors.mobile ?? null"
/>
...
</template>
<script>
import Input from '@Inputs/Input';
export default {
...
components: {
Input,
},
...
}
</script>
Input.vue
<template>
<input
autocomplete="none"
:ref="ref"
:
:type="this.type ?? 'text'"
:value="modelValue"
:disabled="disabled"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script>
export default {
name: 'Input',
inheritAttrs: false,
props: ['type', 'class', 'error', 'modelValue', 'disabled', 'ref']
}
</script>
I even hardcoded the ref attribute with some static value, but the result is same, omitted?
What am I doing wrong here..?
CodePudding user response:
ref
is a special attribute, it's not supposed to work as a prop.
It's possible to access root element of a component as $refs.mobileRef.$el.focus()
. The component can also expose all public methods explicitly, so they would be used as $refs.mobileRef.focus()
.
CodePudding user response:
You can remove the ref
prop in your Input.vue
component and add a watcher inside, to watch for some errors. If there is, trigger a .focus()
on your input element.
Some.vue
<template>
...
<Input
type="number"
name="mobile"
v-model="this.form.mobile"
:
:error="errors.mobile ?? null"
/>
...
</template>
<script>
import Input from '@Inputs/Input';
export default {
...
components: {
Input,
},
...
}
</script>
Input.vue
<template>
<input
autocomplete="none"
ref="mobileRef"
:
:type="this.type ?? 'text'"
:value="modelValue"
:disabled="disabled"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script>
export default {
name: 'Input',
inheritAttrs: false,
props: ['type', 'class', 'error', 'modelValue', 'disabled'],
watch: {
error(val) {
if (val)
this.$refs.mobileRef.focus();
},
},
}
</script>