我的组件如下:
<template>
<div>
<ul class="list-inline list-photo">
<li v-for="item in items">
<div class="thumbnail" v-if="clicked[item]">
<img src="https://myshop.co.id/img/no-image.jpg" alt="">
<a href="javascript:;" class="thumbnail-check"><span class="fa fa-check-circle"></span></a>
</div>
<a v-else href="javascript:;" class="thumbnail thumbnail-upload"
title="Add Image" @click="addPhoto(item)">
<span class="fa fa-plus fa-2x"></span>
</a>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['state', 'product'],
data() {
return {
items: [1, 2, 3, 4, 5],
clicked: [] // using an array because your items are numeric
}
}
},
methods: {
addPhoto(item) {
this.$set(this.clicked, item, true)
}
}
}
</script>
如果我点击一个链接,那么它将调用方法addPhoto
我想如果点击一个链接,它会上传图片。因此,它将选择图像然后上传并更新img并上传图像。
上传图片的代码看起来像是添加照片方法
我仍然很难在vue组件中上传图片
我该如何解决?
答案 0 :(得分:1)
您可以使用文件选择器组件,如下所示:
<template>
<input v-show="showNative" type="file" :name="name" @change="onFileChanged" :multiple="multiple" :accept="accept"/>
</template>
<script>
export default {
props: {
name: { type: String, required: true },
show: { type: Boolean, Default: false },
multiple: { type: Boolean, default: false },
accept: { type: String, default: "" },
showNative: { type: Boolean, default: false }
},
watch: {
show(value) {
if (value) {
// Resets the file to let <onChange> event to work.
this.$el.value = "";
// Opens select file system dialog.
this.$el.click();
// Resets the show property (sync technique), in order to let the user to reopen the dialog.
this.$emit('update:show', false);
}
}
},
methods: {
onFileChanged(event) {
var files = event.target.files || event.dataTransfer.files;
if (!files.length) {
return;
}
var formData = new FormData();
// Maps the provided name to files.
formData.append(this.name, this.multiple ? files : files[0]);
// Returns formData (which can be sent to the backend) and optional, the selected files (parent component may need some information about files).
this.$emit("files", formData, files);
}
}
}
</script>
这里有一些如何使用它的信息:
例如: 单选
<file-upload name="fooImport" @files="selectedFile" :show.sync="true" />
例如: 多选
<file-upload name="barUpload" @files="selectedFiles" :show.sync="displayUpload" accept="text/plain, .pdf" />