LoginSignup
1
1

More than 3 years have passed since last update.

Vue.js 3 : 複数項目のInputで、最後のInputが入力されたら自動的に次のInputを追加する

Last updated at Posted at 2020-11-13

フォームを作っていると、次のように、入力された数が増えた時に、入力欄を自動で追加してほしいことがあります。

image.png

これを Vue.js でやる場合のコードを紹介します。

コード

  <form action='/send_email' method='post'>
    <p>
      メールを送ります。
      送信先のメールアドレスを入力してください。
    </p>
    <div id="email_list">
      <div class="row" v-for="(email, index) in emails">
        {{index + 1}}: <input type="email" name="email[]" v-model="email.value">
      </div>
    </div>
    <button type="submit">Submit</button>
  </form>
  <script>
    Vue.createApp({
      data() {
        return {
          emails: [{value: ''}]
        }
      },
      beforeUpdate() {
        const emails = this.$data.emails
        if (emails[emails.length - 1].value.trim()) emails.push({value:''})
      }
    }).mount('#email_list')
  </script>

beforeUpdate を使って入力値の状態をチェックして入力欄を増やしています。

beforeUpdate は、 データが変更されるとき、DOM が適用される前に呼ばれます。

renderTriggered({key, target, type}) というのもあり、そちらで変更することもできます。 詳しくは Vue.js のライフサイクルのページに載っています。

環境

  • Vue.js 3.0.2
1
1
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
1