目前,我正在使用Vuejs2生成用于图像上传的列表,它将在选择图像文件后显示预览图像,下面是我用Vuejs2:https://codepen.io/anon/pen/MELZKe编写的代码
<div v-for="(image, index) in images" :key="index">
<div class="image-upload">
<label v-bind:for="'cover-upload-' + index">
<img src="http://via.placeholder.com/100x100" width="100" class="preview-img"/>
</label>
<input v-bind:id="'cover-upload-' + index" v-bind:name="'slides[' + index + ']'" type="file" class="upload-preview" style="display:none">
</div>
<button type="button"
@click.prevent="removeImage(index)"
v-show="image_quantity > 1">
Remove
</button>
</div>我创建了2个文件上传图像,上传第一个图像(将预览您的图像),删除第一个预览图像,但它将删除最后一个预览图像而不是第一个。
然而,几乎相同的编码,但使用Vuejs1,它将删除第一个预览图像,而不是最后一个。下面是Vuejs1:https://codepen.io/anon/pen/VMgqbG的代码
我不知道如何为Vuejs2编写这样的情况,或者我必须坚持使用Vuejs1?
谢谢。
发布于 2017-10-19 17:21:16
使用数组的索引作为键是a bad idea。这是因为索引会发生变异。使用正确的密钥,您的问题就解决了。
考虑一下原始代码中的情况,其中图像数组中有两个图像。首先,图像1的索引为0,第二图像的索引为1。当您删除第一个图像时,原来是第二个图像的索引已经更改为零,但是Vue有用于键零的现有DOM元素,这些元素显示位于索引为零的前一个对象的图像。因为Vue有那些键为零的DOM元素,所以它重新使用它们,看起来好像第一个图像没有被删除一样。
console.clear()
new Vue({
el: '#content',
data: {
images: [{ name: '' , id: 1}],
},
computed: {
image_quantity: function () {
return this.images.length;
},
},
methods: {
removeImage: function (index) {
this.images.splice(index, 1);
},
addImage: function (event) {
event.preventDefault();
this.images.push({
name: '',
id: Math.max(...this.images.map(i => i.id)) + 1
});
}
}
});
function readURL(input, preview) {
if (input.files && input.files[0] && input.files[0].type.match('image.*')) {
var reader = new FileReader();
reader.onload = function (e) {
$(preview).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).on('change', '.upload-preview', function () {
readURL(this, $(this).prev().find('.preview-img'));
});<div id="content">
<div v-for="(image, index) in images" :key="image.id">
<div class="image-upload">
<label v-bind:for="'cover-upload-' + index">
<img src="https://via.placeholder.com/100x100" width="100" class="preview-img"/>
</label>
<input v-bind:id="'cover-upload-' + index" v-bind:name="'slides[' + index + ']'" type="file" class="upload-preview" style="display:none">
</div>
<button type="button"
@click.prevent="removeImage(index)"
v-show="image_quantity > 1">
Remove
</button>
</div>
<button type="button" v-on:click="addImage">Create New</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
https://stackoverflow.com/questions/46834623
复制相似问题