1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vue.js】フォームに入力した文字列から自動で空白を取り除く

Posted at

はじめに

Vue.jsの公式ガイドを読んでいたところ、便利な機能を初めて知ったので紹介します。

trim修飾子

v-model.trimをつけるだけで、フォームに入力した文字列から自動で空白を取り除いてくれます。

<script setup>
import { ref } from 'vue'

const message = ref('')
const t_message = ref('')
</script>

<template>
  <p>Message is: {{ message }}</p>
	<input v-model="message" placeholder="edit me" />
  <p>Trimmed message is: {{ t_message }}</p>
	<input v-model.trim="t_message" placeholder="edit me" />
</template>

messageの方は頭の空白がそのままですが、t_messageの方は空白を取り除いて表示されます。

image.png

上の画像では後者の入力欄には空白が表示されていますが、Enterを押した瞬間に入力欄の空白も自動で除去されます。

おわりに

今まで別途バリデーションしていたのですが、今後はこちらを使いたいと思います。

参考

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?