vue制定文章内容模板,文章的每一段对应数组的每一项,支持存放多张图片
demo:
这样的一行,就是文章的一段
用户输入内容时,这一段的内容就会同步到数组中,即第一段的内容会同步到数组的第一项,以此类推(图片会转成base64的格式)。
可以点击“增加一行”来插入段落,相应的,数组也会增加相应的项。
代码:
<template>
<div>
<div
class="edit"
v-for="(item, index) in myFiles"
:key="index"
@click="sendIndex(index)"
>
<el-input v-model="item.text" placeholder="请输入内容"></el-input>
<el-upload
:ref="'upload' + index"
action="123"
list-type="picture-card"
:auto-upload="false"
:on-change="handleChange"
:on-remove="handleRemove"
:on-preview="handlePreview"
:data="pkgFiles"
>
<i slot="default" class="el-icon-plus"></i>
</el-upload>
</div>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
<el-button
style="margin-left: 10px"
size="small"
type="success"
@click="submitUpload"
>上传到服务器</el-button
>
<button @click="addRow">增加一行</button>
</div>
</template>
export default {
data() {
return {
myFiles: [
{
text: "",
image: [],
},
],
pkgFiles: {},
input: "",
dialogImageUrl: "",
dialogVisible: false,
disabled: false,
currentIndex: 0,
};
},
created() {},
updated() {},
methods: {
sendIndex(index) {
this.currentIndex = index;
},
handlePreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
handleRemove(file, fileList) {
let that = this;
let index = this.currentIndex;
var reader = new FileReader();
this.myFiles[index].image = []; //删除时先初始化
// 通过回调函数遍历fileList,并且重新赋值
turnBase64(0);
function turnBase64(j) {
if (j < fileList.length) {
reader.readAsDataURL(fileList[j].raw);
reader.onloadend = function () {
// console.log(reader.result);
that.myFiles[index].image = that.myFiles[index].image.concat(
reader.result
);
turnBase64(++j);
};
}
}
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
handleDownload(file) {},
handleChange(file, fileList) {
/* 点击文件上传后,会初始化一次,此时只剩下upload0有数据,
即发送upload0这个文件,并且为emptyFile,此时状态改变,触发此函数,
所以要判断,如果为空文件,即上传完成了,就不用再赋值了
如果最后一次点击不是第一个,而是第n个,则执行reader.onloadend时,会给myFiles[n].image赋值,
但是已经初始化了,这个值并不存在,因此会报错,赋值失败
(因为数组第n个是个空值,所以不能用.***这种形式赋值,这种形式只有对象才可以用)*/
if (file.raw.name === "emptyFile") {
return;
}
let index = this.currentIndex;
let that = this;
var reader = new FileReader();
reader.readAsDataURL(file.raw);
reader.onloadend = function () {
that.myFiles[index].image = that.myFiles[index].image.concat(
reader.result
);
};
},
submitUpload() {
//转移存储对象
this.pkgFiles.obj = this.myFiles;
//初始化
this.myFiles = [
{
text: "",
image: [],
},
];
const file = new File([], "emptyFile", {
type: "text/html",
});
const sendFile = {
raw: file,
status: "ready",
};
this.$refs.upload0[0].uploadFiles = [sendFile];
// console.log(this.$refs.upload0[0].uploadFiles);
this.$refs.upload0[0].submit();
},
addRow() {
this.myFiles = this.myFiles.concat({ text: "", image: [] });
},
},
};