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