VUE #4 封装一个 wangEditor 组件

以封装 wangEditor 富文本编辑器为例,浅记 VUE 组件封装方式。本篇不涉及 wangEditor 具体使用方法介绍,如需要了解,请移步官网:wangEditor-轻量级 web 富文本编辑器

VUE 版本:3.0。

1. 插件页面定义

<template>
    <div id="demoEditor">

    </div>
</template>

<script>
//导入 WangEditor 插件
import WangEditor from 'wangeditor';

export default {
	//命名空间, 可理解为本页面暴露给外部的名称
    name: 'demoEditor',
    data() {
        return {
            demoEditorHtml: ""
        }
    },
    methods: {
    	//初始化编辑器配置,配置属性为 WangEditor 主流属性
        initEditor() {
            this.demoEditor = new WangEditor('#demoEditor');
            //自定义提示文字
            this.demoEditor.config.placeholder = '自定义提示文字...';
            //一次最多上传 3 张图片
            this.demoEditor.config.uploadImgMaxLength = 3;
            //自定义不需要菜单
            this.demoEditor.config.excludeMenus = [
                'video'
            ];
            //监听内容变化并将内容传递给 demoEditorHtml, 对于外部来说
            //demoEditorHtml 便是封装后的编辑器内容
            this.demoEditor.config.onchange = (html) => {
                this.demoEditorHtml = html;
            };
            this.demoEditor.create();
        }
    },
    mounted() {
        this.initEditor();
    }
}
</script>

2. 引入插件

<template>
    <div class="common-layout">
    	<DEMOEDITOR ref="demoEditor"></DEMOEDITOR>
    	<div style="margin: 10px 0"></div>
        <el-button type="primary" @click="submitEditor()">提交</el-button>
    </div>
</template>

<script>
import demoEditor from '../../components/demoEditor.vue'

export default {
	//注册为组件,重点
    components: {
        DEMOEDITOR:demoEditor
    },
    data() {
        return {}
    },
    methods: {
        submitEditor(){
            //封装后的富文本编辑器内容
            console.log(">>html<<"+this.$refs.demoEditor.demoEditorHtml);
        }
    }
}
</script>

上面的“重点”标记,components 是 VUE 封装组件的精髓所在,DEMOEDITOR 即为封装后的组件在 html 页面使用时的标签名。所以本文全篇其实可归于一词 components,其余内容辅助理解。

3. 看看效果

效果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值