简体   繁体   中英

Accessing a property of the last object in an array in computed vue

I have an empty products array and users can add new products if they want. My goal is I want to save the last productKey and save it in a Vuex state.

//data
products: []

//method
addNewProduct() {
      this.products.push({
        productKey: '',
        productName: ''
      })
},

I want to get the key of the last added product (last object). I've tried this way

lastKey() {
  return this.products[this.products.length-1].productKey
}

This doesn't work as it says cannot read properties of undefined (reading 'productKey') . Any help would be greatly appreciated. thank you.

All state-related (including computed properties) run before hook created .Because products is initially empty so you try to access productKey of last item will result cannot read properties of undefined (reading 'productKey') . You can use optional chaining to check possibility exists.

lastKey() {
  return this.products[this.products.length-1]?.productKey
}

As products is an empty array inside data object and you are assigning the data in it later on by using mounted() or methods .

Initially, computed property always execute before mounted life cycle hook to create the property and at that time products is an empty array. Hence, It is giving cannot read properties of undefined (reading 'productKey') error.

To get rid from this error, You can use Optional chaining (?.) which enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Live demo :

 new Vue({ el: '#app', data: { products: [] }, mounted() { console.log('mounted call'); // This calls this.products.push({ productKey: 'key1', productName: 'name1' }) }, computed: { lastKey: function() { console.log('computed call'); // This calls before mounted life cycle hook to create the lastKey property and it will call again after mounted() as there is a change in the products array. return this.products[this.products.length - 1]?.productKey; } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <p>{{ lastKey }}</p> </div>

I think your code is already correct. this happened because products array is empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM