How to insert link on cursor position of tiptap editor in VueJS?

2.1k views Asked by At

I'm new to VueJS and even more to the tiptap editor that my team is using. I need to make a function that inserts a link at the cursor position within the editor.

I do know about the Link() function with the floating menu bubble. That's already working. But in the web application, they would like to have a pop-up with an option to fill in a display text and a corresponding link, which should be inserted to the editor at cursor position.

Currently, I already have this code:

insertLink(value) {
  let linkToAdd = '<a href="' + value.insertLinkUrl + '" target="_blank">' + value.insertLinkText + '</a>';
  let editorHtml = this.editor.getHTML();
  editorHtml += linkToAdd;
  this.editor.setContent(editorHtml);
}

But, now it appends to the end of the content and also creates a new paragraph tag in which it stores the new generated HTML(?).

Can anybody help me point a little more in the correct direction? That would be very nice.

Thanks in advance!

1

There are 1 answers

0
samurai On

I know it's a bit late to answer and I don't know if it will help anyone in vuejs. This is how i implemented in react.

import Link from "@tiptap/extension-link";

export const CustomLink = Link.extend({
  addCommands() {
    return {
      ...this.parent?.(),
      addLink: function (options) {
        return ({ tr, commands }) => {
          commands.insertContent(
            `<a href='${options.href}' class="custom-link">${options.href}</a>`,
            {
              parseOptions: {
                preserveWhitespace: false,
              },
            }
          );
        };
      },
    };
  },
});