首页 > 解决方案 > Vue CKEditor 分别获取标题和正文

问题描述

如何在 Vue CKEditor 中分​​别获取标题和文本?(像这里

this.editor.getTitle() - this.editor.getTitle 不是函数

this.editor.getBody() - this.editor.getBody 不是函数

this.editor.getTitle - 未定义

this.editor.getBody - 未定义

一段代码:

      data() {
    return {
      editor: ClassicEditor,
      editorData: '<p></p>',
      editorConfig: {
        plugins: [
          Image,
          ImageUpload,
          ImageCaption,
          AutoImage,
          Title,
          AutoSave,
          Heading,
          MediaEmbed,
          HtmlEmbed,
          EssentialsPlugin,
          BoldPlugin,
          ItalicPlugin,
          LinkPlugin,
          ParagraphPlugin,
        ],
        extraPlugins: [cuteUploadAdapterPlugin],
        toolbar: {
          items: [
            'Heading',
            'bold',
            'italic',
            'link',
            'undo',
            'redo',
            'ImageUpload',
            'mediaEmbed',
            'htmlEmbed'
          ]
        },
        heading: {
          options: [
            {model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph'},
            {model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2'},
            {model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3'}
          ]
        },
        title: {
          placeholder: 'title'
        },
        placeholder: 'body',
      },
    };
  },
  methods: {
    buttonClick() {
      console.log(this.editor.getTitle())
      console.log(this.editor.getBody())

标签: javascriptckeditor

解决方案


It seems to work:

    let getTitleAndBody = function () {
    let data = {
      title: '',
      body: '',
    }
    const parser = new DOMParser();
    const doc = parser.parseFromString(editorData, 'text/html');
    const title = doc.getElementsByTagName('h1')[0]
    data.title = title.innerText
    doc.body.removeChild(title)
    data.body = doc.body.innerHTML
    return data;
  }
  let data = getTitleAndBody()
  data.title // get title
  data.body // get body

推荐阅读