Skip to content

Instantly share code, notes, and snippets.

@MinSomai
Last active June 26, 2022 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MinSomai/4f6cde69db926398b1cfaf4f8d7a083a to your computer and use it in GitHub Desktop.
Save MinSomai/4f6cde69db926398b1cfaf4f8d7a083a to your computer and use it in GitHub Desktop.
Slatejs to Vue 3 html serializer - custom render function for SlateJS to vue 3 Vnodes
// How to use?
// Save this file as SerializeContent.js
//
// import SerializeContent from "../SerializeContent";
// <template>
// <SerializeContent :content="content" />
// </template>
import escapeHTML from "escape-html";
import { Text } from "slate";
import { h } from "vue";
const serialize = children => {
return children.map((node, i) => {
if (Text.isText(node)) {
let text = h("span", { key: i, innerHTML: escapeHTML(node.text) });
if (node.bold) {
text = h("strong", { key: i }, text);
}
if (node.code) {
text = h("code", { key: i }, text);
}
if (node.italic) {
text = h("em", { key: i }, text);
}
// Handle other leaf types here...
return h("span", { key: i }, text);
}
if (!node) {
return null;
}
switch (node.type) {
case "h1":
return h("h1", { key: i }, [serialize(node.children)]);
// Iterate through all headings here...
case "h6":
return h("h6", { key: i }, [serialize(node.children)]);
case "quote":
return h("blockquote", { key: i }, [serialize(node.children)]);
case "ul":
return h("ul", { key: i }, [serialize(node.children)]);
case "ol":
return h("ol", { key: i }, [serialize(node.children)]);
case "li":
return h("li", { key: i }, [serialize(node.children)]);
case "link":
return h("a", { href: escapeHTML(node.url), key: i }, [
serialize(node.children),
]);
default:
return h("p", { key: i }, [serialize(node.children)]);
}
});
};
export default {
props: ["content"],
setup(props) {
// `content` should be slatejs value
const { content } = toRefs(props);
return () => [serialize(content.value)];
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment