Skip to content

Instantly share code, notes, and snippets.

@Ishidall
Created April 2, 2020 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ishidall/4edf3de985f62a598ec81fe64919c199 to your computer and use it in GitHub Desktop.
Save Ishidall/4edf3de985f62a598ec81fe64919c199 to your computer and use it in GitHub Desktop.
How to make auto resizing <textarea> by Vue.js
<template>
<textarea
class="textarea bg-white"
:style="textareaStyle"
:placeholder="placeholder"
:value="value"
@input="handleInput($event)"
/>
</template>
<script lang="ts">
import Vue from "vue"
export default Vue.extend({
props: {
placeholder: { type: String, default: "" },
value: { type: String, default: '' }
},
data() {
return {
textareaHeight: 100 // Default value. Same as what you set to minHeight.
}
},
computed: {
textareaStyle(): object { // Necessary for you want to set textarea's height dynamically.
return {
height: `${this.textareaHeight}px`
}
}
},
methods: {
async handleInput(event: any) { // Sorry for being any😭
this.$emit('input', event.target.value)
this.textareaHeight = 0 // Important: Set textarea's height to 0 intentionally.
await this.$nextTick() // IMPORTANT: Without awaiting DOM's update, you'll get StrangelyAutoResizingTextarea.vue
// When height is set to 0, textarea's scrollHeight will get greater so that every line can be shown by scrolling.
// Then you just set that scrollHeight to textarea's height! Hope it helps someone:)
this.textareaHeight = event.target.scrollHeight
}
}
})
</script>
<style lang="stylus" scoped>
.textarea-container {
width: 100%;
}
.textarea {
width: 100%;
min-height: 100px; // If you change here, you should change data()'s textareaHeight.
border: 1px solid #D9D9D9
border-radius: 4px;
padding: 5px 12px;
&::placeholder {
color: #D9D9D9
}
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment