0
votes

I am new to Vue, and just learning it, so I wonder how to modify a component that I have which works fine for the create form, I would like to modified it so that I can use it for the edit form as well. What I need to do is to set the image src to the one I get from the DB if it exists. How can I achieve that? This is the component file:

<template>
<div>
  <div v-if="!image">
    <h2>Select an image</h2>
    <input type="file" @change="onFileChange">
  </div>
  <div v-else>
    <img :src="image" />
    <input type="file" name="image" style="display:none">
    <button @click="removeImage">Remove image</button>
  </div>
</div>
</template>

<script>
export default {
    data() {
        return {
        image: '',
        formData:new FormData(),
        file: null
        }
    },
    methods: {
        onFileChange: function onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createImage(files[0]);
            this.formData.append('file', files[0]);
            this.file = files[0];
        },
        createImage: function createImage(file) {
            var image = new Image();
            var reader = new FileReader();
            var vm = this;
            reader.onload = function (e) {
                vm.image = e.target.result;
            };
            reader.readAsDataURL(file);
        },
        removeImage: function removeImage(e) {
            this.image = '';
        }
    }
}
</script>

I have tried with doing this in my view:

<image-upload :image="/uploads/{{ $magazine->image }}"></image-upload>

But I get the error:

[Vue warn]: failed to compile template ...invalide expression

Update:

I did as suggested in the answers and removed the : from the directive, and it worked but I get a warning message now in the console:

[Vue warn]: The data property "image" is already declared as a prop. Use prop default value instead. (found in component )

1
try removing the : from the image directive. since it's a string it doesn't need processing as a Javascript expression. so <image-upload image="/uploads/{{ $magazine->image }}"></image-upload>Justin MacArthur
Yes, that helped! It works now, but I get a warning message in the console, would you know how to get rid of this: [Vue warn]: The data property "image" is already declared as a prop. Use prop default value instead. (found in component <image-upload>)Marco

1 Answers

4
votes

The prop warning is because you have image in your data property

data() {
    return {
    image: '',
    formData:new FormData(),
    file: null
    }
},

you need to remove it from there and add it to the props property

props: {
    image: {
        type: String,
        default: ""
    }
},
data() {
    return {
    formData: new FormData(),
    file: null
    }
},