3

so I need to have a form input create whenever the user adds a value to the previous input. I've found some great questions about how to create dynamic forms and also how to watch form inputs to call a function but I don't know how to combine the two and make them work together.

new Vue({
  el: '#form',
  data: {
    items: [],
  },
  methods: {
    addItem() {
      this.items.push({
        value: ''
      });
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="form">
  <input v-for="item in items" v-model="item.value">
  <button @click="addItem">add</button> {{items}}
</div>

So currently I can make this work by adding a button to add the new input but the input doesn't show until after you click the button. I tried v-for="item in items + 1" but that cause crazy unexpected results and after I thought about it I realized why that couldn't work. I would really like to have an input box on load and if the user adds any value to that box a new one will be created.

2 Answers 2

8

Ok, I actually just figured it out on my own :p I need to run the function on mount and then use v-on:change.once to run the function.

Now I just need to figure out how to remove the input box when it is empty.

new Vue({
  el: '#form',
  data: {
    items: [],
  },
  methods: {
    addItem() {
      this.items.push({
        value: ''
      });
    }
  },
  mounted() {
    this.addItem()
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="form">
  <input v-for="item in items" v-model="item.value" @change.once="addItem()">
</div>

Sign up to request clarification or add additional context in comments.

Comments

5

Initializing your items with [{ value: '' }] works:

new Vue({
  el: '#form',
  data: {
    items: [{
        value: ''
    }],
  },
  methods: {
    addItem() {
      this.items.push({
        value: ''
      });
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="form">
  <input v-for="item in items" v-model="item.value">
  <button @click="addItem">add</button> {{items}}
</div>

2 Comments

Ah I tried something similar value: [''] but the value wasn't editable that way. I actually solved the issue above but yours is cleaner.
Yeah. I think the logic is the same; You answer adds the object when the component is mounted and mine adds the object as initial value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.