1. 程式人生 > 其它 >vue動態新增刪除富文字(wangEditor)

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());
}