How to render component from a string? #11174
-
I am contemplating a situation where i would write component template on backend server and return it in string form for the front-end to render. This is specifically for a case where i have page template that is dynamic in structure so i cannot have a static component to render it(and no, I cannot actually render it on the backend). I know there is the h() function that can be used to render components. But from the looks of it, https://vuejs.org/guide/extras/render-function.html, there is no way to pass the "template" part of a vue file to it. So how would I go about? |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 2 replies
-
Essentially the problem is that there is no way to compile a template, which can be passed on to the h() function along with props/attributes. The older version of Vue had the option to return template via render() function but that seems to be gone and the h() alone doesn't do anything in this regard. Essentially everything passed to h() must be an element. So having something like a list would require me to pass ul, li, li, li... into h() individually, which as i have said, means each html/vnode element must be separately passed to the h(), not a template as a whole. So I need to find a built-in function that handles the template parsing whenever a vue file is being loaded. |
Beta Was this translation helpful? Give feedback.
-
Looks like this is the thing I am after, now only to figure out how to actually use it |
Beta Was this translation helpful? Give feedback.
-
So there is the |
Beta Was this translation helpful? Give feedback.
-
Here's an article on this exact thing https://medium.com/glovo-engineering/dissecting-vue-3-template-compilation-e01e2b98dafd From what I have seen so far, this is proving to be impossible in Vue 3. |
Beta Was this translation helpful? Give feedback.
-
Do you want this? But now, I can dynamically import a component from a URL/string, and the onServerPrefetch hook will not be executed. |
Beta Was this translation helpful? Give feedback.
-
It's actually quite simple to achieve: <script setup>
import { ref } from 'vue'
const customTemplate = ref('<div>Runtime Template</div>')
setInterval(() => {
// Simulate a template received from the server
const newTemplate = `<div>Runtime Template: ${Math.random()}</div>`
customTemplate.value = newTemplate
}, 500)
</script>
<template>
<component :is="{ template: customTemplate }"></component>
</template> Just make sure to use a Vue build with a runtime compiler, otherwise you'll get a warning for using the |
Beta Was this translation helpful? Give feedback.
It's actually quite simple to achieve:
https://play.vuejs.org/#eNp9U01r4zAQ/StCLCSB1C7s7sU4gd2lhy7sB22POtRrjxNlLclIoyTF+L93JGE3LaU3aWbe03tP0sC/9X129MALXrrayh6ZA/T9VmipemORDcxCy0bWWqPYgkYXQgtdG+2Q1d6hUQ+g+q5CYJswulyUjTxu77xGqYBNzTIP1cUqgOmEW41gj1W3XK7YZssGoRnLc3YvlY9UjWxbsKCR4cRuoQZ5hCYpcQQHG2BJiobThY7HdzUU7NPwq8J9Z…