Hello fellow community members :) I seem to be facing an issue related to reactivity and I could use some advice.
Description
I have a component called FileInput.vue
. This component allows me to upload files to my project. Whenever a new image is added, a new field gets pushed to the form.allImages reactive
array:
@add="addImageField"
The addImageField function looks like this:
const addImageField = (): void => {
form.allImages.push({ filename: '' });
};
Here is the reactive data structure:
import type { Images } from '@/types/images.d';
interface Work {
allImages: Images[];
}
const form: Work = reactive({
allImages: [{ filename: '' }],
});
Problem description
When I add 2 images and then try to delete the first one using the following function:
const deleteImageField = (index: number): void => {
form.allImages.splice(index, 1);
};
The first block gets removed correctly and the second one takes its place as expected. However, the second image block should now be empty with a clear value to allow for another image to be added. Although the value of the second element in form.allImages
is cleared, the component block still displays the image that belonged to the previous first element in the array.
Check out the image here: https://github.com/nuxt/nuxt/assets/73745478/74981582-05ea-4910-9387-7240dc4394c2
Reproduction
You can see the reproduction by visiting this link: https://stackblitz.com/edit/nuxt-starter-qeaeuf?file=app.vue.
How to use the reproduction
Click on the Add Image
block, select any image from your PC, and a static favicon.ico file will be displayed as an example. You will also see a Delete
button for deleting the image. Above all the blocks, you can track the data using the {{ form.allImages }}
.
Expected behavior
After deleting the image block, it should be completely empty (without displaying any image) and ready for the user to upload a new one.
**I appreciate your attention and any help would be greatly appreciated :) If you have suggestions for improving the code, please feel free to share them as well. Thank you.**