我有一個空的產品陣列,用戶可以根據需要添加新產品。我的目標是我想保存最后一個productKey并將其保存為 Vuex 狀態。
//data
products: []
//method
addNewProduct() {
this.products.push({
productKey: '',
productName: ''
})
},
我想獲取最后添加的產品(最后一個物件)的密鑰。我試過這種方式
lastKey() {
return this.products[this.products.length-1].productKey
}
這不像它所說的那樣作業cannot read properties of undefined (reading 'productKey')。任何幫助將不勝感激。謝謝你。
uj5u.com熱心網友回復:
所有與狀態相關的(包括computed屬性)都在 hook 之前運行created。因為products最初是空的,所以你嘗試訪問productKey最后一個專案將導致cannot read properties of undefined (reading 'productKey')。您可以使用可選鏈接來檢查是否存在。
lastKey() {
return this.products[this.products.length-1]?.productKey
}
uj5u.com熱心網友回復:
由于 products 是empty資料物件內部的一個陣列,您稍后使用mounted()or分配其中的資料methods。
最初,computed屬性總是在mounted生命周期鉤子之前執行以創建屬性,當時產品是一個空陣列。因此,它給出了cannot read properties of undefined (reading 'productKey')錯誤。
要擺脫此錯誤,您可以使用可選鏈接 (?.),它使您能夠讀取位于連接物件鏈深處的屬性的值,而無需檢查鏈中的每個參考是否有效。
現場演示:
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>
uj5u.com熱心網友回復:
我認為您的代碼已經正確。發生這種情況是因為 products 陣列為空
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491774.html
標籤:javascript Vue.js
上一篇:在C 中獲取巨大的亂數
