2

У меня есть массив объектов:

items: [
            {id: 1, price: 100},
            {id: 2, price: 150},
            {id: 3, price: 200},
            {id: 4, price: 200},
            {id: 5, price: 200},
            {id: 6, price: 200},
            {id: 7, price: 200},
        ]

Я вывожу эти данные в виде таблицы, где есть поле input type="number". Когда я меняю значения любого input, то меняются все остальные. Как мне сделать, чтобы изменялся только ОДИН, конкретный input ?

Весь код:

<template>
<div class="table-wrapper">
  <h1>{{ title }}</h1>

  <table class="table">
      <thead class="table-header">
          <th>Значение</th>
          <th>Цена</th>
          <th>Количество</th>
          <th>Общая сумма</th>
          <th>Удалить запись</th>
      </thead>
      <tbody>
          <tr  v-for="(item,index) in items" :key="index">
              <td>{{ item.id }}</td>
              <td> {{ item.price }} </td>
              <td><input type="number" name="count-items" id="count-items" v-model="itemCount" @change="changeCount()" min="0" max="100000"></td>
              <td>{{ item.price * itemCount }}</td>
              <td @click="deleteItem(item.id)" class="delete-item">X</td>
          </tr>
      </tbody>
  </table>

  </div>
</template>

<script>
export default {
    name: 'Table',
    components: {},

    props: {},
    

    data() {
        return {
            title: "Таблица расчетов",
            itemCount: '',
            items: [
                {id: 1, price: 100},
                {id: 2, price: 150},
                {id: 3, price: 200},
                {id: 4, price: 200},
                {id: 5, price: 200},
                {id: 6, price: 200},
                {id: 7, price: 200},
            ],
        }
    },

    computed: {}, //для выччисляемых свойств

    methods: { 
        deleteItem: function(id) {
            const index = this.items.findIndex(n => n.id === id)
            this.items.splice(index,1)
        },

        changeCount: function() {
            //
            
        }
    }, 
4
  • 1
    у вас itemCount один на все импуты поэтому он и меняется для всех. в каждый item добавьте свой itemCount и выводите его, тогда всё будет работать 30 ноя 2020 в 14:16
  • 1
    А как его сделать уникальным? Этот itemCount
    – Vanya228
    30 ноя 2020 в 14:20
  • 1
    в каждый item добавьте свой itemCount и выводите его В массиве items у каждого элемента должен быть свой itemCount и в v-model его подставляйте 30 ноя 2020 в 14:27
  • 1
    Мне нужно, чтобы количество я регулировал именно с помощью input, поэтому его нет в массиве items. Т.к в зависимости от этого количества, я буду считать общую сумму товара
    – Vanya228
    30 ноя 2020 в 14:32

2 ответа 2

2

Можно сделать itemCount: {} и v-model подключить как:

<input ... v-model="itemCount[item.id]" ...>

Тогда в itemCount можно будет хранить значение счетчика для каждого из элементов items(если они были изменены) и использовать их для дальнейшей логики

Привожу пример:

new Vue({
  el: '#app',
  data() {
    return {
      title: "Таблица расчетов",
      itemCount: {},
      items: [{
          id: 1,
          price: 100
        },
        {
          id: 2,
          price: 150
        },
        {
          id: 3,
          price: 200
        },
        {
          id: 4,
          price: 200
        },
        {
          id: 5,
          price: 200
        },
        {
          id: 6,
          price: 200
        },
        {
          id: 7,
          price: 200
        },
      ],
    }
  },

  computed: {
    totalCount() {
      let sum = 0;
      for (let key in this.itemCount) {
        sum += +this.itemCount[key];
      }
      return sum
    }
  }, //для вычисляемых свойств

  methods: {
    deleteItem: function(id) {
      const index = this.items.findIndex(n => n.id === id)
      this.items.splice(index, 1)
      Vue.delete(this.itemCount, id)
    },

    changeCount: function() {
      //

    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div class="table-wrapper">
    <h1>{{ title }}</h1>

    <table class="table">
      <thead class="table-header">
        <th>Значение</th>
        <th>Цена</th>
        <th>Количество</th>
        <th>Общая сумма</th>
        <th>Удалить запись</th>
      </thead>
      <tbody>
        <tr v-for="(item,index) in items" :key="index">
          <td>{{ item.id }}</td>
          <td> {{ item.price }} </td>
          <td><input type="number" name="count-items" id="count-items" v-model="itemCount[item.id]" @change="changeCount()" min="0" max="100000"></td>
          <td>
            <template v-if="itemCount[item.id]">
                      {{ item.price * itemCount[item.id] }}
                    </template>
            <template v-else>
                      0
                    </template>
          </td>
          <td @click="deleteItem(item.id)" class="delete-item">X</td>
        </tr>
      </tbody>
    </table>
    Итого: {{ totalCount }}
  </div>
</div>

1

Как вариант:

Vue.config.devtools = false;
Vue.config.productionTip = false;

const app = new Vue({
  el: '#app',
  data() {
    return {
      title: "Таблица расчетов",
      items: [{
          id: 1,
          price: 150,
          count: 5,
        },
        {
          id: 2,
          price: 250,
          count: 15,
        },
        {
          id: 3,
          price: 350,
          count: 7,
        },
        {
          id: 4,
          price: 450,
          count: 12,
        },
      ],
    };
  },
  methods: {
    deleteItem(index) {
      this.items.splice(index, 1);
    },
  },

  computed: {
    totalPrice() {
      return this.items.reduce(
        (curr, {
          count,
          price
        }) => curr + count * price,
        0
      );
    },
    totalCount() {
      return this.items.reduce((curr, {
        count
      }) => curr + count, 0);
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table class="table">
    <thead class="table-header">
      <th>Значение</th>
      <th>Цена</th>
      <th>Количество</th>
      <th>Общая сумма</th>
      <th>Удалить запись</th>
    </thead>
    <tbody>
      <tr v-for="(item, index) in items" :key="index">
        <td>{{ item.id }}</td>
        <td>{{ item.price }}</td>
        <td>
          <input type="number" name="count-items" id="count-items" v-model.number="item.count" min="0" max="100000" />
        </td>
        <td>{{ item.price * item.count }}</td>
        <td @click="deleteItem(index)" class="delete-item">X</td>
      </tr>
    </tbody>
  </table>
  <p>Всего: {{ totalCount }} шт.</p>

  <p>Сумма: {{ totalPrice }} $</p>
</div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.