我是靠谱客的博主 娇气台灯,最近开发中收集的这篇文章主要介绍vue简单封装wangeditor4,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

wangeditor v4版本已经发布了,地址:https://doc.wangeditor.com/

抱着尝鲜的态度在新项目中实践,做了一个简单组件封装

实现思路

  1. 定义常用属性(height/zIndex/placeholder/focus);
  2. 实现v-model指令;
  3. 监听编辑器onchange事件,更新组件value;
  4. watch组件value改变,更新编辑器内容,此处需要注意:在编辑器编辑时,触发onchange事件,更新了组件value值导致watch回调被触发,此时,需判断value与编辑器内容是否相同,相同则不更新编辑器内容;

代码实现

定义常用属性(height/zIndex/placeholder/focus);

@Prop(String) private readonly value?: string;
  
@Prop(Number) private readonly height?: number;

@Prop(Number) private readonly zIndex?: number;

@Prop(String) private readonly placeholder?: string;

@Prop(Boolean) private readonly focus?: boolean;

在mounted生命周期,创建编辑器实例,初始化编辑器配置,监听onchange事件,更新组件value值

mounted() {
    const editor = new WE(this.$el);
    if (this.height) editor.config.height = this.height;
    if (this.zIndex) editor.config.zIndex = this.zIndex;
    if (this.placeholder) editor.config.placeholder = this.placeholder;
    if (this.focus) editor.config.focus = this.focus;
    editor.config.onchange = (html: string) => this.$emit("input", html);
    editor.create();
    editor.txt.html(this.value); // 设置编辑器初始内容
    this.editor = editor;
}

watch组件value改变,更新编辑器内容

 @Watch("value")
 private handleValueChange(value: string) {
    // 防止在编辑时,触发watch
    if (value !== this.editor?.txt.html()) this.editor?.txt.html(value);
 }

完整代码

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import WE from "wangeditor";

@Component({ name: "WangEditor" })
export default class WangEditor extends Vue {
  @Prop(String) private readonly value?: string;

  @Prop(Number) private readonly height?: number;

  @Prop(Number) private readonly zIndex?: number;

  @Prop(String) private readonly placeholder?: string;

  @Prop(Boolean) private readonly focus?: boolean;

  private editor?: WE;

  @Watch("value")
  private handleValueChange(value: string) {
    // 防止在编辑时,触发watch
    if (value !== this.editor?.txt.html()) this.editor?.txt.html(value);
  }

  mounted() {
    const editor = new WE(this.$el);
    if (this.height) editor.config.height = this.height;
    if (this.zIndex) editor.config.zIndex = this.zIndex;
    if (this.placeholder) editor.config.placeholder = this.placeholder;
    if (this.focus) editor.config.focus = this.focus;
    editor.config.onchange = (html: string) => this.$emit("input", html);
    editor.create();
    editor.txt.html(this.value); // 设置编辑器初始内容
    this.editor = editor;
  }
}
</script>

<template>
  <div class="wang-editor"></div>
</template>

 

最后

以上就是娇气台灯为你收集整理的vue简单封装wangeditor4的全部内容,希望文章能够帮你解决vue简单封装wangeditor4所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部