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>