關於動態刪除wangeditor的數據不更新
如何使用wangeditor可以看我上一篇vue+wangEditor (富文本編輯器)
在這個項目中需要富文本,並且還要動態添加刪除,動態添加刪除到是不困難,但是用到了刪除富文本功能時頁面數據不更新的問題,借鑒了https://blog.csdn.net/EnjoyLearning_zn/article/details/109079330中的思路,並用js實現。
思路
刪除之前先,獲取富文本里的所有內容,然后再刪除指定內容,銷毀富文本,再重新創建富文本,最后將獲取的內容設置到富文本里。
動態添加刪除富文本
<template>
<div>
<div v-for="(v, i) of box" :key="i">
<div style="float: left" :ref="v.ref"></div>
<el-button
style="float: left"
icon="el-icon-minus"
@click="delbox(i)"
circle
></el-button>
</div>
<div style="clear: both"></div>
<el-button @click="crebox()">添加</el-button>
</div>
</template>
<script>
import E from "wangeditor";
export default {
data() {
return {
box: [
{
ref: "box",
editor: "editor",
},
],
num: 0,
};
},
methods: {
//刪除
delbox(i) {
//先把所有富文本內容提出來
let arr = [];
for (let q = 0; q < this.box.length; q++) {
arr.push(this.box[q].editor.txt.html());
}
//在按下標刪除
arr.splice(i, 1);
this.box = [];
//重新創建富文本
for (let w = 0; w < arr.length; w++) {
setTimeout(() => {
this.crebox(arr[w]);
}, 15);
}
},
//添加
crebox(val) {
this.num++;
let ref = "box" + this.num;
this.box.push({
ref,
});
let box = this.box[this.box.length - 1];
setTimeout(() => {
box.editor = new E(this.$refs[ref]);
box.editor.config.height = 70;
box.editor.create();
if (val) {
box.editor.txt.html(val);
}
}, 10);
},
},
mounted() {
this.box[0].editor = new E(this.$refs.box);
this.box[0].editor.config.height = 70;
this.box[0].editor.create();
},
};
</script>
最后就是獲取富文本內容
for (let i = 0; i < this.box.length; i++) {
console.log(this.box[i].editor.txt.html());
}