Search code examples
vue.jsvuejs2vuejs3inertiajs

Vuejs. Cannot set properties of undefined (setting)


data() {
        return {
            qty_to_order: null,
        }
    },

methods: {
        showQty(product_id) {
            this.carts.filter(function(cart) {
                if (cart.product_id === product_id) {
                    this.qty_to_order = cart.qty_to_order
                }
            })
        }
    }

When I call the method, I get an error. How to write cart.qty_to_order to this.qty_to_order (in data) ?

This method works

showQty(product_id) {
            this.carts.filter(function(cart) {
                if (cart.product_id === product_id) {
                    console.log(cart.qty_to_order)
                }
            })
        }

Solution

  • You need to understand how the this keyword works. The reason why it does not work is because if you use a function() {} as the callback the value of this is the window. If you use an arrow function, then you will get the correct value of this. Here is a great blog post about how the this keyword works in javascript.

    <script>
    export default {
      data() {
        return {
          qty_to_order: null,
          carts: [{
            product_id: 1,
            qty_to_order: 1
          }]
        }
      },
      methods: {
        showQty(product_id) {
          this.carts.filter((cart) => {
            console.log(this)
            if (cart.product_id === product_id) {
              this.qty_to_order = cart.qty_to_order
            }
          })
        }
      }
    }
    </script>
    
    <template>
      <button @click="showQty(1)">show qty</button>
    </template>