Rodrigo Silva
Rodrigo Silva

Reputation: 387

How to insert content inside tinymce editor using vue js?

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.

Upvotes: 2

Views: 6573

Answers (4)

Black Beard
Black Beard

Reputation: 1618

I finally gave up trying to get access to tinymce in Vue 3 component. It either undefined or if it is not undefined - setContent command just do nothing - no errors but still no content inserted.
I just used recommended for "@tinymce/tinymce-vue" way of data binding using v-model
It looks like this:

<Editor
      v-model="someLocalVar"
      api-key="no-api-key"
      :init="{
            plugins: 'lists link image table code help wordcount',
       }"
/>

then

watch(someLocalVar, () => {
        //do whatever you like with your someLocalVar
});

Upvotes: 1

mikyone
mikyone

Reputation: 41

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');

Upvotes: 4

Tiny Lincoln
Tiny Lincoln

Reputation: 1102

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)

Upvotes: 2

Michael Fromin
Michael Fromin

Reputation: 13744

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>');

Upvotes: -2

Related Questions