article

Thursday, February 17, 2022

Vue.js Vue CLI Image Upload Preview

Vue.js Vue CLI Image Upload Preview

C:\vuejs\my-vue-app>npm run serve

src/App.vue
//src/App.vue
<template>
  <div id="app">
    <h1>Vue.js Vue CLI Image Upload Preview</h1>
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld from './components/filePreview.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
src/components/filePreview.vue
//src/components/filePreview.vue
<template>
  <div>
    <div class="imagePreviewWrapper" :style="{ 'background-image': `url(${previewImage})` }" @click="selectImage"> </div>

    <input ref="fileInput" type="file" @input="pickFile">
  </div>
</template>

<script>
export default {
  data() {
      return {
        previewImage: null
      };
    },
  methods: {
      selectImage () {
          this.$refs.fileInput.click()
      },
      pickFile () {
        let input = this.$refs.fileInput
        let file = input.files
        if (file && file[0]) {
          let reader = new FileReader
          reader.onload = e => {
            this.previewImage = e.target.result
          }
          reader.readAsDataURL(file[0])
          this.$emit('input', file[0])
        }
      }
  }
}
</script>

<style>
.imagePreviewWrapper {
    width: 250px;
    height: 250px;
    display: block;
    cursor: pointer;
    margin: 0 auto 30px;
    background-size: cover;
    background-position: center center;
}
</style>

Related Post