vue动态添加删除富文本(wangEditor)

关于动态删除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());
}
posted @ 2021-10-30 09:36  默永  阅读(1269)  评论(0编辑  收藏  举报