I want to have a photo preview in my code below. I'm working with BootstrapVue.
But I don't know where the problem is.. after looking in my Vue devtools I can see that the form-file has the picture, but my "watch" is not working..
It would be very helpful if someone can help me out !
My template:
<template>
<div>
<div v-for="item in files" :key="item.id">
<b-button v-b-toggle="item.id" variant="danger btn-block mb-2">
Upload {{ item.id }}</b-button>
<b-collapse :id="item.id" class="mt-2">
<div class="m-2 mt-3">
<table class="table table-striped mt-2">
<tbody>
<div class="mt-3 mb-2 ml-1">Upload</div>
<b-form-file
:v-model="item.request"
placeholder="Upload ..."
class="mb-2"
></b-form-file>
<b-img
v-if="item.request"
:src="item.src"
class="mb-3"
fluid
block
rounded
></b-img>
</tbody>
</table>
</div>
</b-collapse>
</div>
</div>
</template>
My script:
<script>
const base64Encode = (data) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(data);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
export default {
data() {
return {
files: [
{ id: "1", src: null, request: null },
{ id: "2", src: null, request: null },
{ id: "3", src: null, request: null },
],
};
},
watch: {
files: {
deep: true, //watch changes at objects properties
handler(newValue, oldValue) {
if (newValue !== oldValue) {
if (newValue) {
base64Encode(newValue.src)
.then((value) => {
newValue.src = value;
})
.catch(() => {
newValue.src = null;
});
} else {
newValue.src = null;
}
}
},
},
},
};
</script>
CodePudding user response:
You made a little mistake!
Instead of writing :v-model
for b-form-file
component use v-model
.
In watch property you cannot understand which upload inputs changed. So try using input
event handler for b-form-file
. Then you can pass index of each files
and run base64Encode
function.
You can see working version of your code here.