0

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`;
        }
    },

1 Answer 1

2

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`;
    }
},
Sign up to request clarification or add additional context in comments.

1 Comment

As many other posts demonstrate, using $ref on mounted sometimes works, sometimes not. Didn't work for me in this example. I think the questioner is making a good point: Isn't there an event handler for mounted (similar to the standard onload), so that his inputChange could be used on both?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.