在vue中使用wangEditor富文本编辑器

显示效果

第一步:安装   npm i wangeditor --save

第二步:创建一个  editorTemplate.vue  

                   把他当做一个富文本组件,在需要的页面使用

                        // 引入 wangEditor

                         import wangEditor from 'wangeditor'

                         //创建editor实例

                         const editor = new wangEditor(`#demo1`)


 editorTemplate.vue的代码

<template>

  <div class="home">

    <h3>wangEditor with vue</h3>

    <div id="demo1"></div>

    <button type="button" class="btn" @click="getEditorData">

      获取当前内容

    </button>

    <!-- <h3>内容预览</h3>

    <textarea name="" id="" cols="170" rows="20" readonly style="width:100%" v-model="editorData"></textarea> -->

  </div>

</template>

<script>

// 引入 wangEditor

import wangEditor from "wangeditor";

export default {

  data() {

    return {

      editor: null,

      editorData: "",

    };

  },

  mounted() {

    const editor = new wangEditor(`#demo1`);

    // 配置 onchange 回调函数,将数据同步到 vue 中

    editor.config.onchange = (newHtml) => {

      this.editorData = newHtml;

      this.$emit("editorContent", newHtml);

    };

    // 创建编辑器

    editor.create();

    this.editor = editor;

  },

  methods: {

    getEditorData() {

      // 通过代码获取编辑器内容

      let data = this.editor.txt.html();

      alert(data);

    },

  },

  beforeDestroy() {

    // 调用销毁 API 对当前编辑器实例进行销毁

    this.editor.destroy();

    this.editor = null;

  },

};

</script>

<style lang="scss" scoped>

.home {

  width: 1200px;

  margin: auto;

  position: relative;

  .btn {

    position: absolute;

    right: 0;

    top: 0;

    padding: 5px 10px;

    cursor: pointer;

  }

  h3 {

    margin: 30px 0 15px;

  }

}

</style>

第三步:创建父组件wangEditor.vue

wangEditor.vue的代码

<template>

  <div class="content">

    <h1>WangEditor样例</h1>

    <wang-editor @editorContent="getEditorContent" />

    <div class="show">

      <h3>内容预览</h3>

      <textarea

        name=""

        cols="170"

        rows="20"

        readonly

        style="width: 100%"

        v-model="editorData"

      ></textarea>

    </div>

  </div>

</template>

<script>

// 引入子组件

import WangEditor from "./editorTemplate";

export default {

  name: "app",

  components: {

    WangEditor,

  },

  data() {

    return {

      // 编辑器内容

      content: "",

      editorData: "",

    };

  },

  methods: {

    // 获取编辑器内容

    getEditorContent(data) {

      //将获取的Html转成纯文本

      this.editorData = data.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');  ;

    },

  },

};

</script>

<style lang="scss" scoped>

.content {

  width: 100%;

}

.show {

    width: 80%;

  margin: 0 auto;

}

h3 {

  margin: 30px 0 15px;

}

</style>


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。