I'm using Quasar and Vue.js to create a form where I can add objects into an array so they can be inserted into the DB all at the same time, but whenever I add or delete one object from this array it just updates after I focus on any other input in the form, it is adding and deleting the objects from the array as it should, but it isn't showing on the screen unless I focus on any other input in the form, follow the code:
<template>
<form>
<q-input
v-model = "eventTitle"
label = "Event title"
/>
<div
v-for = "(task, index) in tasks" :key = "index"
>
<q-btn
label = "Remove Task"
@click = "removeTask(index)"
/>
<q-input
v-model = "task.title"
label = "Title"
/>
<q-input
v-model = "task.date"
label = "Date"
/>
<q-input
v-model = "task.desc"
label = "Description"
/>
</div>
<q-btn
label = "Add Task"
@click = "addTask"
/>
</form>
</template>
<script>
export default {
setup () {
const singleTask = {
title: '',
date: '',
desc: ''
}
var tasks = []
return {
tasks,
singleTask
}
},
methods: {
addTask() {
this.tasks.push(this.singleTask)
},
removeTask(index) {
this.tasks.splice(index, 1)
}
}
}
</script>
And whenever I edit a field on one object the others are also modified (which is another problem). If someone has any suggestions on this one I'll be grateful because I've never seen something like this.
Thanks for the suggestions and answers beforehand.
Multiple problems here:
singleTask is a single object instance. Pushing it into array will not create a copy of the object. As a result your array contains multiple items - references to an object all pointing to a single object. Google for "JS value vs reference" to understand the concept
You are using setup but data structures returned from it are not reactive data. You need to use ref or reactive
Do not use index as the key - it same as not using key at all. key must be stable - meaning it should "connect" any single object in the iterated array to a DOM element (or group of elements) created for it by Vue. Index is not stable as it changes when you delete items from the array
Last piece of advice: combining Composition API and Options API is not recommended. Either use one or another. Excellent new tutorial can help