C:\vuejs\my-vue-app>npm run serve
src/App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //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> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | //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> |