定义一个简单的模板
const templates = `<div @click="handleClick">Hello, {{ name }}!</div>`;
使用 @vue/compiler-dom 生成最终的代码,编译模板字符串为渲染函数。
import { compile } from '@vue/compiler-dom';const { code } = compile(templates);
代码如下:
const _Vue = Vuereturn function render(_ctx, _cache) {with (_ctx) {const { toDisplayString: _toDisplayString, openBlock: _openBlock, createElementBlock: _createElementBlock } = _Vuereturn (_openBlock(), _createElementBlock("div", { onClick: handleClick }, "Hello, " + _toDisplayString(name) + "!", 9 /* TEXT, PROPS */, ["onClick"]))}
}
开始使用
import { ref, createApp } from 'vue';
import * as Vue from 'vue';const render = new Function('Vue', code)(Vue);const app = createApp({setup(props, { expose }) {const name = ref('world');const handleClick = () => {name.value = 'hello'};return () => {return render({ name, handleClick })}}
});app.mount('#app')