Issue
This Content is from Stack Overflow. Question asked by SpaceKraken
I’m creating a component that needs to render out of a bunch of concated strings. Vue’s compile
and h
functions accomplish this quite nicely while having access to the parent context (unlike the template option).
However, the compiled text itself has no access to the parent context. Here’s my simplified code:
<script setup>
import {compile, h, computed } from 'vue'
const props = defineProps(['commTemplate', 'content']);
const textStyle = computed(() => ({
fontSize: props.commTemplate.textSize + 'px',
}));
const titleTyle = computed(() => ({
fontSize: props.commTemplate.titleSize + 'px',
}));
const structure = [];
const parts = [];
structure[0] = `
<table>
<tr>
<td :style="textStyle"></td>
<td>
`; parts['thing'] = `
</td>
<td :style="titleStyle">Optional Part</td>
<td>
`; structure[1] = `
</td>
</tr>
</table>
`;
const render = () => {
return h(compile(structure[0] + parts['thing'] + structure[1]));
};
</script>
<template>
<render />
</template>
After running this, Vue complains about textStyle
not being defined when it encounters :style="textStyle"
.
Is there any way to render/compile this along with the parent context?
Solution
Any props can be passed on to the rendered component using something like this:
return h(compile('template'), { prop1, prop2 });
This Question was asked in StackOverflow by SpaceKraken and Answered by SpaceKraken It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.