我想删除图像src,这是我的模板
<div class="file-upload-section">
<label id="preview" for="file-upload">
<img v-if="url" :src="url" />
</label>
<div class="file-upload">
<label class="file-upload-button" for="file-upload">Upload Image</label>
<input type="file" id="file-upload" @change="onFileChange"/>
</div>
<div v-if="url">
<button @click="removeImage()">Remove image</button>
</div>
</div>这是我的剧本
data: function () {
return {
url: null,
file: null
}
},
methods: {
onFileChange (e) {
this.file = e.target.files[0]
this.url = URL.createObjectURL(this.file)
},
removeImage: function () {
this.url = null
}
}
}这就是我所做的一切,是我做错了什么,还是有另一种方法可以从img中删除一张图片。
发布于 2021-03-13 11:45:13
编辑:
在测试您的代码时,我注意到文件预览确实重置了( url变量),但是输入的值没有。我想这就是你的意思,因此:
您可以在文件输入上使用ref,并将其重置。
在输入中添加一个引用:<input type="file" id="file-upload" ref="file" @change="onFileChange"/>
另外,相应地更新您的removeImage方法:
removeImage: function () {
this.url = ""
this.$refs.file.value = ""
}发布于 2021-03-13 08:20:19
您的代码正在运行;我在我的环境中尝试过它。它工作得很完美。问题可能是重新呈现。我删除了"file“变量,因为基于您的代码,这似乎没用,我在onFileChange function中创建了作用域变量。
要修复重呈现问题,请在"img“标记中添加键,并给它一个唯一的值,该值将在”添加“和”删除“图像上更改。在下面的例子中,我使用"URL“作为键。
<img :key="url" v-if="url" :src="url" />下面是代码,试一试:
<template>
<div class="file-upload-section">
<label id="preview" for="file-upload">
<img :key="url" v-if="url" :src="url" />
</label>
<div class="file-upload">
<label class="file-upload-button" for="file-upload">Upload Image</label>
<input type="file" id="file-upload" @change="onFileChange"/>
</div>
<div v-if="url">
<button @click="removeImage()">Remove image</button>
</div>
</div>
</template>
<script>
export default {
data: function () {
return {
url: null
}
},
methods: {
onFileChange (e) {
let file = e.target.files[0]
this.url = URL.createObjectURL(file)
},
removeImage: function () {
this.url = null
}
}
}
</script>发布于 2021-03-13 08:08:43
在Vuejs中,为了绑定一个事件,您应该使用v-on:click或以简短的方式:单击:
<button :click="removeImage">Remove image</button>https://stackoverflow.com/questions/66611082
复制相似问题