原来这就是[封装Vue组件]

以为自己对Vue的使用已经很熟练了,但是被别人问到有没有你自己封装过一个组件时,瞬间懵逼了。每个Vue文件都是一个组件,这算吗?显然是不算的,因为这是业务文件。自己封装的Vue组件应该是可以复用于其他页面中的公共组件。想了一下,其实我也做过啊,现在就来复盘一下吧。

在一个项目中用到富文本编辑器,试了好几个都不满意,最后找到wangEditor挺合适的,现在就来对它做一个封装。

首先,根据文档下载安装并完成初始化

npm install wangeditor

研究下作者提供的demo:

template部分

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

script部分

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

作者提供的配置文档:

https://www.kancloud.cn/wangfupeng/wangeditor3/332599

我需要一个页面有多个编辑器,看文档是根据div的id属性来区分,但是在每个容器上面都初始化了一遍,我们不确定每个页面有几个编辑器,所以需要动态设置。
我也需要修改已经保存的内容,即把后端返回的内容再在编辑框内展现出来,所以需要设置html属性,content用于查看返回内容:

<div>
<div :id="ID"></div>
{{content}}
</div>

js部分:

import E from 'wangeditor'
export default{
data(){
return{
content:''
}
},
props:['ID','html'],
mounted(){
var editor = new E(`#${this.ID}`);
editor.customConfig.onchange = (html) => {
this.content = html
}
editor.create()
editor.txt.html(this.html)//返回的富文本重新赋值给编辑器用于修改内容
}
}

使用组件的时候再这样:

<Editor :ID="desc_id" :html="desc_html"></Editor>

根据大神花裤衩的说法这就完成了封装一个组件,原来这么简单,这我做过啊 ==!


加强版:上面的那个只是一个非常简单的封装,但是我们的编辑器需要更多的功能,比如上传图片再显示在编辑器里,同时我又想自己个性化定制一下菜单,不需要的功能统统不要出现。这时候我们就需要对照文档做一下更多的配置了:

import E from 'wangeditor'
export default{
data(){
return{
content:''
}
},
props:['ID','html'],
mounted(){
var editor = new E(`#${this.ID}`);
editor.customConfig.zIndex = 100;
editor.customConfig.menus = [
'head', // 标题
'bold', // 粗体
'italic', // 斜体
'underline', // 下划线
'strikeThrough', // 删除线
'foreColor', // 文字颜色
'backColor', // 背景颜色
'link', // 插入链接
'list', // 列表
'justify', // 对齐方式
'quote', // 引用
'image', // 插入图片
'table', // 表格
'undo', // 撤销
'redo' // 重复
];
editor.customConfig.uploadImgServer = '/file/upload_file.do';//图片上传地址
editor.customConfig.withCredentials = true;//允许跨域
editor.customConfig.uploadImgParams={};
editor.customConfig.uploadFileName = 'file';
editor.customConfig.uploadImgHooks = {
customInsert: function (insertImg, result, editor) {
var url = result.body.url
insertImg(url)
}
}
editor.customConfig.onchange = (html) => {
this.content = html
}
editor.create()
editor.txt.html(this.html)//返回的富文本重新赋值给编辑器用于修改内容
}
}

后面的部分可以直接参考大神的手摸手文章,写的很详细。

参考