Home » vue » How to insert content inside tinymce editor using vue js?

How to insert content inside tinymce editor using vue js?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I want to insert content like <span class="some-class">text</span> inside tinymce editor using a button in vue js template. How could I accomplish that using the tinymce-vue wrapper?
Here’s the code:

<template>
  <tinymce-editor
    api-key="my-api-key-here"
  />
  <button @click="addContent">button</button>
</template>

import Editor from '@tinymce/tinymce-vue'

export default {
  components: {
    tinymceEditor: Editor
  },
  methods: {
    addContent () {
      tinymce.activeEditor.setContent('<span class="some-class">text</span>');
    }
  }
}

Edit:

I also installed tinymce using npm i tinymce --save and added the import import tinymce from 'tinymce/tinymce to the code above. Now I don’t get the error 'tinymce' is not defined anymore, but the editor doesn’t appear either.

Answers:

In your event handler for the button click, you can call TinyMCE’s .setContent() method to set editor content.

Here is a demo:
https://codesandbox.io/s/set-content-in-tinymce-in-vue-jzciu

Don’t forget, tinymce-vue doesn’t include the code for TinyMCE itself. You’ll either have to use an API key (which you can get for free at tiny.cloud) or use a self-hosted installation of TinyMCE. (For more info, see Step 6, here: https://www.tiny.cloud/docs/integrations/vue/#procedure)

###

If you want to use tinymce in vue with typscritt to set up your content and avoid the undefined error you need to import tinyMCE as

import { getTinymce } from '@tinymce/tinymce-vue/lib/cjs/main/ts/TinyMCE';

Then you can set your content

 getTinymce().activeEditor.setContent('coucou');

###

If you want to insert content into TinyMCE you should use its APIs to do so:

https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#setcontent
https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#insertcontent

For example:

tinymce.activeEditor.setContent('<span class="some-class">text</span>');
tinymce.activeEditor.insertContent('<span class="some-class">text</span>');