Skip to content

设置和获取 HTML

获取 HTML

  • editor.getHTML() 获取编辑器内容(带 html 标签)

  • editor.getText() 获取编辑器内容(不带 html 标签)

设置 HTML

  • editor.setHTML(html) 设置编辑器内容
vue
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
  <button @click="getcontent">提交HTML</button>
  <button @click="gettext">提交text</button>
  <button @click="handlesetHtml">设置HTML</button>
  <div
    v-html="setHtmlContent"
    style="width: 80%; height: 80px; border: 1px solid #ccc; margin-top: 10px"
  ></div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";

// 编辑器实例,必须用shallowRef包裹

const editorRef = shallowRef();

// 内容HTML

const valueHtml = ref("");

// 编辑器模式

const mode = ref("default"); // simple或者default;

// 模拟ajax异步获取数据内容

onMounted(() => {
  setTimeout(() => {
    // valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
    const toolbar = DomEditor.getToolbar(editorRef.value);
    const curToolbarConfig = toolbar.getConfig();
    console.log(curToolbarConfig.toolbarKeys);
  }, 1500);
});

// 工具栏配置

const toolbarConfig = {};

// 编辑器配置

const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁的时候,也即时 销毁编辑器

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 编辑器示例

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录editor实例
};

// 获取到编辑器内容

const getcontent = () => {
  window.alert(editorRef.value.getHtml());
};

// 获取到文本内容

const gettext = () => {
  window.alert(editorRef.value.getText());
};

// 设置HTML

const setHtmlContent = ref("<p>哈哈哈</p><p>hello23232</p>");

const handlesetHtml = () => {
  editorRef.value.setHtml(setHtmlContent.value);
};
</script>

<style scoped lang="scss"></style>