JoerJoers's avatar

Vue Component for Image Upload: Pass Image Source from View

I'm trying to pass the image source from the view to the vue component however, it doesn't work at all. Please help me figure this out. Thank you.

Vue Component

<template>
  <div>
    <div class="form-group">
      <label for="photo_preview">Photo Preview</label>
      <figure>
        <img :src="imageData" class="preview">
      </figure>
    </div>
    <div class="form-group form-group--upload">
      <div class="form-group__avatar">
        <img src="/images/avatar-empty.png" alt="">
        <div class="form-group__label">
          <h6>Character Photo</h6>
          <span>40x40 min size</span>
        </div>
      </div>
      <div class="form-group__upload">
        <label class="btn btn-default btn-xs btn-file">
          Upload Image <input type="file" @change="previewImage" name="photo" id="photo" style="display: none;" accept="image/*">
        </label>
      </div>
    </div>
  </div>
</template>

<script>
    export default {
        data() {
          return {
            imageData: ""
          }
        },

        methods: {
          previewImage: function(event) {

            var input = event.target;

            if (input.files && input.files[0]) {

                var reader = new FileReader();

                reader.onload = (e) => {

                    this.imageData = e.target.result;
                }

                reader.readAsDataURL(input.files[0]);
            }
          }
        }
    }
</script>

View

<upload-photo imageData='{{ $character->photo }}'></upload-photo>
0 likes
4 replies
favor's avatar

You should do: <upload-photo :imageData='{{ $character->photo }}'></upload-photo>

Since you are passing a prop, add the props array to your vue component.

<script>
    props: ['imageData'],
    export default {
        data() {
          return {
            imageData: "" //you might not need this
          }
        },
JoerJoers's avatar
JoerJoers
OP
Best Answer
Level 8

Thanks for your @favor.

But i found out the issue.

I should do

<upload-photo image-data='{{ $character->photo }}'></upload-photo>

instead of

<upload-photo :imageData='{{ $character->photo }}'></upload-photo>
1 like

Please or to participate in this conversation.