In my VueJS application, I am attempting to dynamically create a sensorArray
. However, when I create an element, delete it, and then try to create a new one, I encounter the following error:
client.js:227 TypeError: Cannot read properties of undefined (reading 'value')
at eval (templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./pages/Test.vue?vue&type=template&id=cde3d4aa&:44)
at Proxy.renderList (vue.runtime.esm.js:2643)
Below is a snippet of my simple Vuejs application:
<template>
<div>
<span>Sensor Information : </span>
<button class="btn btn-info" @click="addSensorInfo($event)">
Add Sensor
</button>
<br>
<span v-if="sensorArray.length > 0"><b>Sensor Element: </b></span>
<span v-if="sensorArray.length > 0">
<div v-for="sensor in sensorArray" :key="sensor.ID" class="form-group">
<label class="form-label">Value</label>
<input v-model="sensorArray[sensor.ID].value" type="text" class="form-control">
<button class="btn btn-danger" @click="deleteSensorInfo($event,sensor.ID)"><i class="bi bi-trash" /></button>
</div>
</span>
</div>
</template>
<script>
export default {
data () {
return {
sensorID: 0,
sensorArray: []
}
},
methods: {
addSensorInfo (event) {
event.preventDefault()
const sensor = {}
sensor.ID = this.sensorID
this.sensorArray.push(sensor)
this.sensorID++
},
deleteSensorInfo (event, sensorID) {
event.preventDefault()
this.sensorArray.splice(this.sensorArray.filter(obj => obj.ID === sensorID), 1)
}
}
}
</script>
- Click on
Add Sensor
button: A text field and delete button will appear. - Click on
Delete ICON
and delete the field. - Now click on
Add Sensor
again and I receive the following error:
client.js:227 TypeError: Cannot read properties of undefined (reading 'value')
Since I have many elements within my SensorArray
, I am not creating dedicated elements and instead trying to create everything dynamically based on user clicks. Can someone please advise me on how to resolve this issue?