0

I have the following component:

<template>
  <div>    
    <form @submit.prevent="formSubmit()">
    <input type="text" class="form-control" v-model="amount">
    <button class="btn btn-primary" style="width: 100%">Buy</button>
    </form>
  </div>

</template>
     
<script>

export default {

  props:{


  },


  computed: {
    amount() {
      return this.$store.getters.amount
    },
  },
  methods: {
      formSubmit() {
          let currentObj = this;
          
          console.log(this.amount)

          axios.post('MY-BACKEND', {        
              amount: this.amount,

          },

          .then(function (response) {
            currentObj.output = response.data;
          }.bind(this))

          .catch(function (error) {
              currentObj.output = error;
          });
      },
  
  }
}

</script>

This is a standard form with an input text field. The problem with my code is that when i input the field, the value of amount is not what i input into the field, but it is always the default value that this.$store.getters.coinBalance sets it to. So suppose that when i load the component the value of amount is 60 and i input in the field 120, the value of amount stays 60. How can i fix this?

1 Answer 1

2

You are getting the amount from the store but you didn't update it when your input changes. To update the amount value in the store, you can create a setter for your computed property:

computed: {
  amount: {
    get() {
      return this.$store.getters.amount
    },
    set(val) {
      this.$store.commit('updateAmount', val)
    }
  },
},

And in your store create a mutation updateAmount to update amount:

updateAmount(state, amount) {
  state.amount = amount
}
Sign up to request clarification or add additional context in comments.

12 Comments

Thank you a lot! I already have a mutation to update it, but what i mean is that: can i get the value of amount i input in the field without having to call the mutation?
You can bind the amount to a data property, i.e. have something like data() { return { amount: 60 } } and remove computed amount, but then the changes won't be updated in the store.
Ok! I tried this, but the value of amount keeps staying the same. Suppose when i open the page the default value of amount is 100, if i input into the input text field "5" and i hit the Buy button, the value should be the one i input but instead it's still 100
the value should be the one i input but instead it's still 100, which value is this ? Did you get the value from the store or it's the local amount value ?
Indeed, i needed a created lifecycle
|

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.