|
| 1 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 2 | +import {Vue2CompileResult} from '@/utils/types-helper' |
| 3 | +import {Vue, defineComponent, VNode, h, PropType, isVue2} from 'vue-demi' |
| 4 | + |
| 5 | +// Use weak map to store the mapping relationship between ctx and {[template]: renderFunction} |
| 6 | +// This memory will be automatically reclaimed when other references to ctx are destroyed (related to the browser memory reclamation mechanism) |
| 7 | +const compileMap = new WeakMap<Object, Record<string, Function>>() |
| 8 | + |
| 9 | +/** |
| 10 | + * compile a template to render function |
| 11 | + * @param template template string |
| 12 | + * @param ctx context |
| 13 | + * @returns render function |
| 14 | + */ |
| 15 | +const compile = (template: string, ctx: Object): Function => { |
| 16 | + const historyResults = compileMap.get(ctx) |
| 17 | + if (historyResults && historyResults[template]) return historyResults[template].bind(ctx) |
| 18 | + |
| 19 | + let renderFunc: Function |
| 20 | + if (isVue2) { |
| 21 | + const compileResult = Vue.compile(template) as unknown as Vue2CompileResult |
| 22 | + renderFunc = compileResult.staticRenderFns?.[0] ?? compileResult.render |
| 23 | + } else { |
| 24 | + renderFunc = Vue.compile(template) |
| 25 | + } |
| 26 | + |
| 27 | + const results = { |
| 28 | + ...historyResults, |
| 29 | + [template]: renderFunc |
| 30 | + } |
| 31 | + compileMap.set(ctx, results) |
| 32 | + return renderFunc.bind(ctx) |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * template render component |
| 37 | + * |
| 38 | + * @example |
| 39 | + * ```jsx |
| 40 | + * <x-tpl :tpl="yourTemplate" :ctx="this" /> |
| 41 | + * |
| 42 | + * export default { |
| 43 | + * data() { |
| 44 | + * return { |
| 45 | + * name: 'xiao ming', |
| 46 | + * yourTemplate: '<div>hello, {{name}}</div>' |
| 47 | + * } |
| 48 | + * } |
| 49 | + * ``` |
| 50 | + */ |
| 51 | +const vm = defineComponent({ |
| 52 | + name: 'XTpl', |
| 53 | + props: { |
| 54 | + tpl: { |
| 55 | + type: String |
| 56 | + }, |
| 57 | + ctx: { |
| 58 | + type: Object as PropType<Record<string, any>> |
| 59 | + } |
| 60 | + }, |
| 61 | + render() { |
| 62 | + const {$props, $parent} = this as InstanceType<typeof vm> |
| 63 | + const {tpl, ctx} = $props |
| 64 | + const _ctx = ctx || $parent || {} |
| 65 | + |
| 66 | + // console.log('render', isVue2, tpl, _ctx) |
| 67 | + |
| 68 | + if (!tpl) return null |
| 69 | + |
| 70 | + const renderFunc = compile(tpl, _ctx) |
| 71 | + const result = isVue2 ? renderFunc(h) : renderFunc(ctx) |
| 72 | + |
| 73 | + return result as VNode |
| 74 | + } |
| 75 | +}) |
| 76 | + |
| 77 | +export default vm |
0 commit comments