I am trying to learn composition API and move away from options api as vue3 seems to be moving towards it. I am doing a simple example where a user enters in an input box the ticker and then the number of shares in the input box next to it. When you click off it adds it to the array of positions. However, I am trying to tie into the clear event on the input boxes and if you click the clear button then Quasar has a clear event it triggers. I am running a function deletePosition to delete that row which should update the array and delete that row. My issue however is this deletes all items in the array except the 0 index which is 'AAPL' stock. It does not matter how many positions I add it still does this unusual behavior. I am not sure why this keeps happening and its making me wonder should I not be using ref and should be using reactive or am I just missing something obvious?
<template>
<q-page >
<form id="upload-stocks-form" method="post">
<h1 >Add Positions</h1>
<div >
<template v-for="(item,index) in positionsArray" :key=index>
<div >
<q-input filled v-model="item.StockSymbol" @clear="deletePosition(index)" label="Stock Symbol" clearable>
</q-input>
</div>
<div >
<q-input filled v-model.number="item.ShareCount" type="number" label="Shares">
</q-input>
</div>
</template>
<div >
<q-input filled v-model="addStockSymbol" label="Add New Stock Symbol" @blur="addPosition">
</q-input>
</div>
<div >
<q-input filled v-model.number="addShareCount" type="number" label="Shares" @blur="addPosition">
</q-input>
</div>
<div >
<q-btn color="orange-8" label="Save" />
</div>
</div>
</form>
</q-page>
</template>
<script>
import {watch, ref, defineComponent} from 'vue'
export default defineComponent({
name: 'UploadPositions',
components: {
},
setup () {
//v-models
const addStockSymbol = ref('')
const addShareCount = ref('')
const positionsArray = ref([{StockSymbol: 'AAPL', ShareCount: 4 },{StockSymbol: 'AMD', ShareCount: 10 }])
//methods
const addPosition = () => {
if((addStockSymbol.value != null && addStockSymbol.value != '') && (addShareCount.value != null && addShareCount.value != '')){
positionsArray.value.push({StockSymbol: addStockSymbol.value.toUpperCase(), ShareCount: addShareCount.value})
addStockSymbol.value = null
addShareCount.value = null
console.log(positionsArray.value)
}
}
const deletePosition = (index) => {
positionsArray.value = positionsArray.value.splice(index,1)
console.log(positionsArray.value)
}
return {
addStockSymbol, addShareCount, positionsArray, addPosition, deletePosition
}
}
})
</script>
CodePudding user response:
splice
will return the deleted item, so the positionsArray
will be the deleted items only.
You just don't need to re-assign positionsArray
const deletePosition = (index) => {
positionsArray.value.splice(index,1)
}