vue+element-ui中使用WangEditor编辑器

WangEditor是一个比较新开源在线编辑器,支持将图片转base64按文本文件提交,在一些简单的系统中可以省不少事(至少免去了搞上传系统和附件管理系统)。

如何将WangEditor和Vue+Element-UI整合起来,官网语焉不详,仅提供了一个范例。我看了一些博客的引入办法是直接在页面中引入的,这里我把我的组件式引入方法和踩的坑介绍一下。

先在npm下安装wangeditor:

npm install wangeditor --save

首先,查看官网的Vue引入编辑器源码,可以看到Vue是以组件形式引入的:

(源码位于wangEditor/example/demo/in-vue/src/路径下)

<template>
    <div>
        <div ref="editor" style="text-align:left"></div>
        <button v-on:click="getContent">查看内容</button>
    </div>
</template>

<script>
    import E from 'wangeditor'
    export default {
      name: 'editor',
      data () {
        return {
          editorContent: ''
        }
      },
      methods: {
        getContent: function () {
            alert(this.editorContent)
        }
      },
      mounted() {
        var editor = new E(this.$refs.editor)
        editor.customConfig.onchange = (html) => {
          this.editorContent = html
        }
        editor.create()
      }
    }
</script>

<style scoped>
</style>

我们将这个组件取名为Editor.vue放到我们工程的component目录下,在需要引用的页面内加入:

<template>
  <div id="article_editor">
    <editor></editor>
  </div>
</template>

<script>
import Editor from './components/Editor'
export default {
  name: 'article_editor',
  components: {
    Editor
  }
}
</script>

就可以了。这样,编辑器就是以组件形式引入工程的。

然后,我们还要做的是从父组件(表单页)获取子组件(编辑器)的内容:

<Editor v-bind:content="editForm.content"></Editor>

同时,子组件做了以下修改:

1.增加content属性,接收父组件传值。

2.分离编辑器和工具栏,实现编辑器尺寸自动变化。

3.绑定content和editorContent的值,以便父页面获取。

<template>
<div>
    <div id="toolbar" class="toolbar">
    </div>
    <div style="padding: 1px 0; background-color: #ccc"></div>
    <div id="editor" class="text" style="min-height:400px;border:1px solid #ddd;"> <!--可使用 min-height 实现编辑区域自动增加高度-->

    </div>
</div>
</template>

<script>
    import E from 'wangeditor'
    export default {
      name: 'Editor',
      data () {
        return {
          editorContent: ''
        }
      },
	  props:{
		content:{
			type:String,
			required:false
		}
	  },
      methods: {
        getContent: function () {
			this.content=this.editorContent;
        }
      },
      mounted() {
        var editor = new E("#toolbar","#editor")
		editor.customConfig.uploadImgShowBase64 = true ;
        editor.customConfig.onchange = (html) => {
          this.editorContent = html
        }
        editor.create()
		editor.txt.html(this.content);
      }
    }
</script>

<style scoped>
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章