Loading

wangEditor富文本编辑器

代码

<template>
  <div class="app">
    <div class="btns">
      <el-button type="primary" @click="getContent"
        >获取编辑器当前输入的内容</el-button
      >
      <el-button size="small" type="primary" @click="getHTML"
        >获取html</el-button
      >
      <el-button size="small" type="primary" @click="setHTML"
        >重置后重新设置html</el-button
      >
      <el-button size="small" type="primary" @click="insertNode"
        >插入节点</el-button
      >
    </div>
    <div style="border: 1px solid #ccc">
      <!-- <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      /> -->
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onChange="handleEditorChange"
      />
    </div>
  </div>
</template>

<script>
import $ from 'jquery'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'simple', // or 'simple'
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
    },
    handleEditorChange(editor) {
      console.log(editor.children)

      // 获取dom区的节点
      const elements = this.editor.getEditableContainer()
      // // 获取所有行
      const p_els = $(elements).find('p')
      p_els.each((index, p) => {
        console.log(p)
      })
      // console.log(p_els)
    },
    getContent() {
      console.log(this.editor.getText())
    },
    getHTML() {
      console.log(this.editor.getHtml())
    },
    setHTML() {
      this.editor.clear()
      this.editor.dangerouslyInsertHtml(`<h1>标题</h1><p>文本 <b>加粗</b></p>`)
    },
    insertNode() {
      const node = { type: 'paragraph', children: [{ text: 'simple text' }] }
      this.editor.insertNode(node)
    },
  },
  // mounted() {
  //   // 模拟 ajax 请求,异步渲染编辑器
  //   // setTimeout(() => {
  //   //   this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
  //   // }, 1500)
  // },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时,及时销毁编辑器
  },
}
</script>

<style lang="less" scoped>
#editor—wrapper {
  border: 1px solid #ccc;
  z-index: 100; /* 按需定义 */
}
#toolbar-container {
  border-bottom: 1px solid #ccc;
}
#editor-container {
  height: 200px;
}

.btns {
  margin-bottom: 10px;
}
</style>

posted @ 2024-04-12 08:13  ^Mao^  阅读(43)  评论(0编辑  收藏  举报