当您点击"选择文件"并选择要上传的图像,但会出现路径。只有在您单击"选择文件"再一次。
如何解决此问题并在选择文件时上传?
非常感谢任何帮助。谢谢。
new Vue({
el: '.app',
data: {
userImage: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length) {
return
}
this.createImage(files[0])
},
createImage(file) {
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.userImage = e.target.result
}
reader.readAsDataURL(file)
},
removeImage: function (e) {
this.userImage = ''
}
}
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-xs-6 text-center app">
<img class="profile-image" :src="userImage" />
<div v-if="!userImage">
<input type="file" round class="change-profile-image" @change="onFileChange" />
</div>
<div v-else>
<button class="delete-profile-image" color="secondary" icon="delete" @click="removeImage">Delete</button>
</div>
</div>
&#13;
我的代码JSfiddle。
答案 0 :(得分:0)
您不应该依赖于收听click
事件。你要找的是change
事件,即使用@change
代替@click
:
<input type="file" round class="change-profile-image" @change="onFileChange" />
请参阅更新的小提琴:https://jsfiddle.net/hrtzezk8/5/或下面的概念验证片段:
new Vue({
el: '.app',
data: {
userImage: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length) {
return
}
this.createImage(files[0])
},
createImage(file) {
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.userImage = e.target.result
}
reader.readAsDataURL(file)
},
removeImage: function (e) {
this.userImage = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-xs-6 text-center app">
<img class="profile-image" :src="userImage" />
<div v-if="!userImage">
<input type="file" round class="change-profile-image" @change="onFileChange" />
</div>
<div v-else>
<button class="delete-profile-image" color="secondary" icon="delete" @click="removeImage">Delete</button>
</div>
</div>