Reputation: 4539
Learning Vue so this may be a basic question. I have a component that renders a textarea input:
<textarea
v-if="$attrs.type === 'textarea'"
v-bind="$attrs"
:value="value"
@input="inputChange"
:class="[
error ? 'text-red-500' : 'text-gray-600',
textareaAutoResized ? 'h-32' : '',
inputClass,
]"
></textarea>
My inputChange
method works well:
methods: {
inputChange(evt) {
let value = evt.target.value
this.$emit('input', value)
if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
evt.target.style.height = "auto";
let newHeight = evt.target.scrollHeight;
evt.target.style.height = `${newHeight}px`;
}
},
},
But I cannot get the textarea to auto size on page load based on initial content. How do I access the element on mounted? Thanks!
mounted() {
if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
this.$el.style.height = "auto";
let newHeight = this.$el.scrollHeight;
this.$el.style.height = `${newHeight}px`;
}
},
Upvotes: 0
Views: 1930
Reputation: 4424
You can use $ref
on your <textarea>
:
<textarea
ref="textarea"
v-if="$attrs.type === 'textarea'"
v-bind="$attrs"
:value="value"
@input="inputChange"
:class="[
error ? 'text-red-500' : 'text-gray-600',
textareaAutoResized ? 'h-32' : '',
inputClass,
]"
></textarea>
and get it on mounted:
mounted() {
if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
this.$refs.textarea.style.height = "auto";
let newHeight = this.$refs.textarea.scrollHeight;
this.$refs.textarea.style.height = `${newHeight}px`;
}
},
Upvotes: 2