LoginSignup
3
3

More than 3 years have passed since last update.

vueで改行に合わせて伸縮するテキストフォーム

Posted at

実装

textareaを利用することを想定。rowsの値を変更してformを伸び縮みさせている。

function fitToForm(target: HTMLFormElement, text: string, defaultRows = 1): void {
    const lines = text.match(/\n/g)?.length || 1;
    if (defaultRows <= lines) {
      target.rows = lines + 1;
    }
    if (defaultRows > lines) {
      target.rows = defaultRows;
    }
}

利用イメージ

v-model渡しているstateをfitToFormの第二引数に渡しています。
第三引数にtextareaのデフォルトのrowsを設定すると、それ以上小さくなりません。

<textarea
    v-model="comment"
    placeholder="コメントを入力"
    rows="4"
    type="text"
    @input="fitToForm($event.target, state.comment, 4)"
/>

完成gif

May-17-2020 14-58-11.gif

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3