Skip to content
Advertisement

Input not updated when incrementing with button on VueJS

I have two components called OrderComponent and ModalOrder (with vue-modal-js)

I passed the data from OrderComponent to ModalOrder, and in ModalOrder, I use an input tag to contain quantity_ordered and button to increment its value like this

<!-- ModalOrder.vue -->
<input v-model="order.quantity_ordered" />
<button @click.prevent="increment"></button>

in my script tag

// ModalOrder.vue
<script>
export default {
  name: "ModalOrder",
  methods: {
    beforeOpen (event) {
      // if there's a data passed from the OrderComponent, I put it to "order" data
      this.order = event.params

      // if there's no data passed a.k.a a new record, I have to set the default value to 0
      if (this.order.quantity_ordered == undefined) { 
        this.order.quantity_ordered = 0
      }
    },
    ...
    increment() {
      this.order.quantity_ordered += 1
      // this method will not increment the input UI, if it's a new record
    },
  },
  data() {
    return {
      order : {
        code: '',
        table_name: '',
        customer_name: '',
        employee_name: '',
        menu_name: '',
        quantity_ordered: ''
      },
    }
  }
}
</script>

My problem is whenever I want to make a new order data, then when I click the button to increment, the input value UI isn’t incrementing

Thank you in advance.

Advertisement

Answer

You’re falling prey to one of Vue’s change detection caveats

Vue cannot detect property addition or deletion

So for your new records, you would need to either set the property when you assign the new value to order

this.order = {
  quantity_ordered: 0,
  ...event.params // if "quantity_ordered" is set here, it will override the default.
}

or dynamically set it after

if (this.order.quantity_ordered == undefined) { 
  this.$set(this.order, 'quantity_ordered', 0)
}

As mentioned in the comments, you should also default your data property to 0 if it’s meant to be numeric

data: () => ({
  code: '',
  table_name: '',
  customer_name: '',
  employee_name: '',
  menu_name: '',
  quantity_ordered: 0 // 👈
})
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement