1

I'm pretty new with Vue and I am trying to add another input box (which I have as a separate component), when clicking on a button.

<div>
    <Input id="school" label="school" class="school-input" />
</div>

When clicking on a button, I want to add another input field.

<Button btn-text="add new school" type="btn-edit" @click="add()" />

But I don't know what should I put in the add() method (since the input box is a component, and not just a regular html input), so that when I click on the button, I get a new empty input box below the existing one.

Thanks for your help and references.

2
  • please provide the vue or current component instance Commented Jul 26, 2020 at 15:48
  • Actually I don't have much code. I'm just having the input as a separate component where I have: <input :id="id" :type="type" :placeholder="placeholder" :disabled="disabled" :value="value" @input="$emit('input', $event.target.value)" /> And I was using this as a reference: codepen.io/izobiz/pen/vgeWaY But I am really confused because here we are adding a new html element when clicking on the button, and I need to create an instance of the Input component... Commented Jul 26, 2020 at 16:01

1 Answer 1

1

Add a data property called schools which is initialized as an array and iterate over it using v-for then bound each school to an Input :

Vue.component('Input', {
  props: ['value'],
  template: `<input  :value="value" @input="$emit('input', $event.target.value)" />`
})

let app = new Vue({
  el: '#app',
  data() {

    return {
      schools: [{
        name: ''
      }]
    }
  },

  methods: {
    add() {
      this.schools.push({
        name: ''
      })
    }
  }


})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="add">add new Schoold
</button>
  <Input v-for='(school,index) in schools' v-model="schools[index].name"></Input>

  <h3>schools:</h3>
  <pre>{{schools}}</pre>
</div>

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

Comments

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.