How can I store the value of each input into vuex?

799 Views Asked by At

This is my "Test.vue"components


    <template>
    <div>
      <div>
          <button  @click="decrenumber (id)">-</button>
          <input name="test" type="text" :key="id" v-model.number="num">
          <label for="test" ></label>
          <button @click="increnumber (id)">+</button>
      </div>
    </div>
    </template>
    <script>
    import { mapState } from 'vuex';
    
    export default {
      name: 'Test',
      data() {
        return {
          num: 0,
        };
      },
      props: {
        id: { type: Number, default: 0 },
      },
      methods: {
        increnumber(id) {
          this.num += 1;
          this.$emit('update', this.num);
        },
        decrenumber(id) {
          this.num -= 1;
          this.$emit('update', this.num);
        },
      },
    };
    </script>

And I have 5 Test.vue components in my TestView.vue


    <template>
        <div >
           <Test :id="index" v-for="(n,index) in 5" @update="selfUpdate"></Test>
        </div>
    </template>
    <script>
    
    import Test from '../components/Test.vue';
    
    export default {
      name: 'TestView',
      components: {
        Test,
      },
      data() {
        return {
          inputValue: 0,
        };
      },
      methods: {
        selfUpdate(num) {
          this.inputValue = num;
          this.$store.state.test.number = this.inputValue;
        },
      },
    };
    </script>

How can I store the value of each input from TestView.vue into vuex? I know it is possible to use array.push() but this keeps increasing How did I just make the input only exist in five indexes, If you enter the input in the same field, it can replace the old value

1

There are 1 best solutions below

1
On

To save the value of each input you'll need a key pair of input/value for each input, this way when updating a value you will know which one to update.

I adjusted the component to save each value;

The first change is on the template, it calls the method selfUpdate and passes the value emitted by the component as well the input index, so the inputValues will be updated only for that specific input.

The second adjustment is on an assignment of the value, it's assigned to a position that refers to the input, that's why the index is passed along with the value.

<template>
  <div >
    <Test
        :id="index"
        v-for="(n,index) in 5"
        @update="(num) => selfUpdate(num, index)"
    />
  </div>
</template>
<script>

import Test from '../components/Test.vue';

export default {
  name: 'TestView',
  components: {
    Test,
  },
  data() {
    return {
      inputValues: []
    };
  },
  methods: {
    selfUpdate(num, index) {
      this.inputValue[index] = num; // saves the value at index `index`
      this.$store.state.test.number = this.inputValue;
    },
  },
};
</script>