一、安装 Wangeditor

首先,你需要在你的 Vue 项目中安装 Wangeditor。可以通过 npm 或 yarn 进行安装:

npm install wangeditor --save
# 或者
yarn add wangeditor

二、初始化 Wangeditor

在 Vue 组件中,你可以通过以下步骤初始化 Wangeditor:

  1. <template> 中添加一个用于承载 Wangeditor 的容器。
  2. <script> 中引入 Wangeditor。
  3. 创建 Wangeditor 的实例。

以下是初始化 Wangeditor 的示例代码:

<template>
  <div ref="editor"></div>
</template>

<script>
import E from 'wangeditor';

export default {
  mounted() {
    const editor = new E(this.$refs.editor);
    editor.config.menus = ['head', 'bold', 'fontSize', 'italic', 'underline', 'strikeThrough', 'textColor', 'bgColor', 'emoticon', 'undo', 'redo'];
    editor.create();
  }
}
</script>

在上面的代码中,我们首先在 <template> 中添加了一个名为 editor 的 div 容器,然后在 <script> 中引入了 Wangeditor。在 mounted 生命周期钩子中,我们创建了一个 Wangeditor 实例,并配置了可用的菜单项。

三、自定义 Wangeditor 功能

Wangeditor 提供了丰富的配置选项,你可以根据自己的需求进行自定义。以下是一些常用的自定义配置:

  • menuConfig:配置菜单项。
  • uploadImgShowBase:是否以 Base 的形式显示图片。
  • uploadImgServer:图片上传的服务器地址。

以下是一个自定义 Wangeditor 功能的示例:

<script>
import E from 'wangeditor';

export default {
  data() {
    return {
      uploadImgServer: 'http://example.com/upload'
    };
  },
  mounted() {
    const editor = new E(this.$refs.editor);
    editor.config.menus = ['head', 'bold', 'fontSize', 'italic', 'underline', 'strikeThrough', 'textColor', 'bgColor', 'emoticon', 'undo', 'redo'];
    editor.config.uploadImgServer = this.uploadImgServer;
    editor.config.uploadImgShowBase = true;
    editor.create();
  }
}
</script>

四、获取和设置内容

Wangeditor 提供了获取和设置内容的方法,方便你在组件中与其他功能进行交互。

  • getContent():获取编辑器内容。
  • setText(content):设置编辑器内容。

以下是一个获取和设置内容的示例:

<template>
  <div ref="editor"></div>
  <button @click="getContent">获取内容</button>
  <button @click="setText">设置内容</button>
</template>

<script>
import E from 'wangeditor';

export default {
  mounted() {
    const editor = new E(this.$refs.editor);
    editor.config.menus = ['head', 'bold', 'fontSize', 'italic', 'underline', 'strikeThrough', 'textColor', 'bgColor', 'emoticon', 'undo', 'redo'];
    editor.create();
  },
  methods: {
    getContent() {
      const content = this.$refs.editor.getContent();
      alert(content);
    },
    setText() {
      const content = '这是要设置的内容';
      this.$refs.editor.setText(content);
    }
  }
}
</script>

在上面的代码中,我们添加了两个按钮,分别用于获取和设置编辑器内容。通过调用 getContent()setText() 方法,我们可以方便地获取和设置编辑器内容。

五、总结

通过本文的介绍,相信你已经学会了如何在 Vue 中使用 Wangeditor 实现所见即所得编辑体验。Wangeditor 功能丰富,配置灵活,非常适合在 Vue 项目中使用。希望本文能帮助你更好地掌握 Wangeditor。