使动态的输入量个性化

时间:2019-06-26 15:34:36

标签: vue.js

我正在尝试基于下拉菜单中的选择创建多个名称输入。现在,如果我输入一个输入,则所有输入的值都相同。如何使它们全部独立,以便可以动态地将x个名称发布到Firebase?

<template>
    <div>
        <form v-on:submit.prevent="addRsvp">
            <div>
                <label>How many people are attending?</label>
                <select v-model="selected">
                    <option v-bind:value="{ number: 1 }">1</option>
                    <option v-bind:value="{ number: 2 }">2</option>
                    <option v-bind:value="{ number: 3 }">3</option>
                </select>
            </div>

            <div>
                <label>Names:</label>
                <input
                    type="text"
                    v-for="n in Number(selected.number)"
                    v-bind:index="n"
                    v-model="newRsvp.name"
                    :key="n"
                />
            </div>

            <div>
                <input type="submit" value="SUBMIT"/>
            </div>
        </form>
    </div>
</template>
<script>

import { db } from '../config/db';

export default {
    name: 'HomePage',
    firebase: {
        rsvp: db.ref('rsvp'),
    },
    data () {
        return {
            selected: {
                number: 2,
            },
            newRsvp: {
                name: '',
            },
        }
    },
    methods: {
        addRsvp() {
            this.$firebaseRefs.rsvp.push({
                name: this.newRsvp.name,
            })
            alert("Succeessfully added");
        }
    }
}

</script>

1 个答案:

答案 0 :(得分:0)

您需要一个名称数组,而不是单个对象。如何更改代码以实现此目的的示例:

...
<input
  type="text"
  v-for="(n, index) in Number(selected.number)"
  v-bind:index="n"
  v-model="newRsvps[index].newRsvp.name"
  :key="n"
/>
...
data() {
  return {
    ...
     newRsvps: [] // array of new names
  }
},
watch: {
  'selected.number': {
    handler: function(newVal) {
      this.newRsvps = Array.from({length:newVal}).map(x => ({newRsvp: {name: ''}})
    },
    immediate: true
  }
}