Osman Ali
Osman Ali

Reputation: 135

Array of inputs, with last field always blank for new add

JSBin and Stackoverflow snippet are below.

I am trying to have a list of input components. If all input components are filled with a value (not blank), then there should be a "new blank field" visible at the end for the user to type into. When he types into it, it should make this field apart of the list above it, maintaining focus in it.

However the problem I'm having is, focus maintains in the new field, and never moves into the array. Here is my code:

JSBIN and stackoverflow snippet - https://jsbin.com/cudabicese/1/edit?html,js,output

const app = new Vue({
  
  el: '#app',
  
  data: {
    inputs: [
      { id:'foo', value:'foo' },
      { id:'bar', value:'bar' }
    ]
  },
  
  methods: {
    addRow(e) {
      this.inputs.push({
        id: Date.now(),
        value: e.target.value
      })
    },
    deleteRow(index) {
      this.inputs.splice(index, 1)
    }
  }
  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
  <div id="app">
    
    <ul>
      <li v-for="(input, index) of inputs">
        <input type="text" v-model="input.value">
      </li>
      <li v-if="inputs.filter(input => !!input.value).length">
        <input type="text" @input="addRow">
      </li>
    </ul>
    
  </div>

Upvotes: 0

Views: 23

Answers (1)

Wesley
Wesley

Reputation: 26

I'd recommend you put the input for the list within a computed function vs directly using the data. The examples at https://v2.vuejs.org/v2/examples/ are a good place to start.

Upvotes: 1

Related Questions