The vue rich text editor TinyMCE sets some tags in the content to be non-editable

Scenario: When using the rich text editor TinyMCE to set up a message template, you need to embed some fixed tags. The fixed tags are used to dynamically assemble data when parsing the template in the background. The embedded tags are in text format and are easily modified by mistake, resulting in the inability to parse the fixed tags. Label

As shown in the picture:

Clicking on a page’s fixed tag will insert the tag text at the cursor position in the rich text editor.

Solution: We need to set the label text to a non-editable state, so as to avoid misoperation. The rich text editor provides a plug-in (noneditable) that can set the element to be non-editable. We use this plug-in and some APIs and time to achieve this. this function.

Introduce plugin:

You can then use the `init` method to initialize the editor and set up a `setup` callback function to handle the editor’s events and custom functions.

setup: function (editor) {
editor.on('init', function () {
this.getBody().style.fontSize = '14px';
// After the editor initialization is completed, set some content to be non-editable.
const body = editor.getBody();
// Get the elements that need to be set as non-editable
const elementsToMakeNonEditable = body.querySelectorAll('.non-editable');
// Traverse elements and set them to non-editable
elementsToMakeNonEditable.forEach((element) => {
editor.dom.setAttrib(element, 'contenteditable', false);
});
})

// Listen to the editor's change event, obtain the latest content, and set some content to be non-editable
editor.on('change', () => {
const body = editor.getBody();
// Get the elements that need to be set as non-editable
const elementsToMakeNonEditable = body.querySelectorAll('.non-editable');
// Traverse elements and set them to non-editable
elementsToMakeNonEditable.forEach((element) => {
editor.dom.setAttrib(element, 'contenteditable', false);
});
});
}

In the initialization and change listening methods, we specify that elements whose class is non-editable are configured in a non-editable state. Therefore, when we insert a fixed label in the message template, we only need to add a class to the fixed label.

After inserting the fixed template content, we need to manually trigger the change method

The rich text editor object is obtained according to the actual situation. There are multiple text editors placed on my page, so the object acquisition is implemented in the onBlur method.

Implementation effect: The inserted tag cannot be modified and can only be deleted as a whole

The complete code of the rich text editor component: