Created
August 22, 2024 18:17
-
-
Save marcelocra/cb29d89f5a36821f5d1fb472fb0cddbd to your computer and use it in GitHub Desktop.
How to use Vue with JavaScript tagged literals and HTM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { default as htm } from 'htm'; | |
import { RouterLink, RouterView } from 'vue-router'; | |
import { ref, h } from 'vue'; | |
// A component with something like: | |
// | |
// export default { | |
// setup(_props, { slots }) { | |
// return () => h('div', slots.default()); | |
// } | |
// } | |
// | |
import Header from './Header.js'; // A component. | |
const html = htm.bind(h); | |
export default { | |
setup() { | |
const counter = ref(0); | |
// More Vue setup code here... | |
// This is the render function. | |
return () => h( | |
'div', | |
{ class: 'flex flex-col gap-3' }, // Other props here. | |
[ | |
// Use `htm` only. | |
html` | |
<${Header}> | |
${() => { | |
// `Header` only has a default slot, which is why this | |
// internal function is not named. Must be a function | |
// otherwise Vue complains. If you have more slots, pass | |
// an object here instead (replace the whole ${} thingy): | |
// | |
// ${{ default: func1, otherSlot: func2 }} | |
// | |
return html` | |
<${RouterLink} to="/home">${() => "Home"}<//> | |
<${RouterLink} to="/about">${() => "About"}<//> | |
`; | |
} | |
<//> | |
`, | |
// Mix `htm` with the `h` function. | |
h( | |
Header, | |
{}, | |
{ | |
// Uses the `default` slot. If you only use the default one, you | |
// can pass the function directly, like in the example above. | |
default: () => [ | |
h(RouterLink, { to: "/home" }, () => "Home"), | |
h(RouterLink, { to: "/about" }, () => "About"), | |
html`<${RouterLink} to="/about">${() => "About2"}<//>`, | |
], | |
}, | |
), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment