feat(runtime-vapor): template

This commit is contained in:
三咲智子 Kevin Deng 2023-11-09 17:54:31 +08:00
parent bf6778b5bd
commit ef9628ce7f
No known key found for this signature in database
GPG Key ID: 69992F2250DFD93E
4 changed files with 38 additions and 4 deletions

View File

@ -1,3 +0,0 @@
test('basic', () => {
//
})

View File

@ -0,0 +1,17 @@
/**
* @vitest-environment jsdom
*/
import { template } from '../src'
describe('api: template', () => {
test('create element', () => {
const t = template('<div>')
const div = t()
expect(div).toBeInstanceOf(HTMLDivElement)
const div2 = t()
expect(div2).toBeInstanceOf(HTMLDivElement)
expect(div2).not.toBe(div)
})
})

View File

@ -1 +1 @@
export const foo = 'bar'
export { template } from './template'

View File

@ -0,0 +1,20 @@
export const template = (str: string): (() => Node) => {
let cached = false
let node: Node
return () => {
if (!cached) {
cached = true
const t = document.createElement('template')
t.innerHTML = str
// first render: insert the node directly.
// this removes it from the template fragment to avoid keeping two copies
// of the inserted tree in memory, even if the template is used only once.
return (node = t.content.firstChild!)
} else {
// repeated renders: clone from cache. This is more performant and
// efficient when dealing with big lists where the template is repeated
// many times.
return node.cloneNode(true)
}
}
}