D
D
Dauren S2019-01-03 14:02:02
Vue.js
Dauren S, 2019-01-03 14:02:02

Adding a Vue.js newline and inserting an index (line number) by default?

<div id="app">
  <h1>Add user</h1>
  <div v-for="(user, index) in users">
    <select v-model="user.name">
      <option value="">Выбрать</option>
      <option v-for="o in getOptions(index)" :value="o.value" v-text="o.label"></option>
    </select>
    <input v-model="user.procent">

    <button @click="deleteUser(index)">
      delete
    </button>
  </div>

  <button @click="addUser" :disabled="users.length >= options.length">
    New User
  </button>

  <pre>{{ users }}</pre>
  <pre>{{ percentTotal }}</pre>
</div>

new Vue({
  el: '#app',
  data: {
    users: [{ name: '', procent: '' }],
    options: [
      { label: 'Иванов', value: 'ivanov' },
      { label: 'Петров', value: 'petrov' },
      { label: 'Титарев', value: 'titarev' },
    ]
  },
  methods: {
    getOptions(index) {
      return this.options.filter(o => this.users.every((u, i) => u.name !== o.value || i === index));
    },
    addUser() {
      this.users.push({ name: '',procent:'' });
    },
    deleteUser(index) {
      this.users.splice(index, 1);
      if (this.users.length === 0) {
        this.addUser();
      }
    },
  },
  computed: {
    percentTotal() {
      return this.users.reduce((acc, user) => acc + parseInt(user.procent, 10), 0)
    },
 	},
});

How to insert index number by default when adding new line to input?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2019-01-03
@dauren101

addUser() {
    this.users.push({
        name: '',
        procent: this.users.length,
    });
},

G
grinat, 2019-01-03
@grinat

For example, open Google, find out that push returns the new length of the array, subtract one from there and hob, you have what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question