[Vuejs]-Vue.js – which function to use to parse received html fragment with vue tags?

1👍

You have a few options, but I would favor using v-html myself.

It would not be difficult to define a new component programmatically and set its template: Vue’s template compilation can be expensive, and modern Vue tooling tries to do as much of it at TS compilation time as possible and avoid shipping the template compiler as a runtime dependency. If you do choose to use a new template at runtime, make sure you are using a build that contains the compiler at runtime.

Instead, however, you can treat the server side XHTML as external and use it to set the v-html directive. You won’t need template compilation; Vue will just treat that as a source of opaque HTML, and you can use normal DOM traversal through a ref to add event listeners after the fact using plain JS and DOM functions.


If I were a new developer visiting your codebase, I would be surprised to see your template logic existing in two places (Vue and also server side). It’s not the most jarring, but I would naturally wonder why the table wouldn’t just come through as JSON to let Vue do what you’re clearly using Vue for.

That acknowledged, it would feel even weirder to have your generated XHTML emit Vue templates, because then that obligates your servlet caller to use Vue in just the way that works with your client side. That tight coupling prevents reuse of your XHTML generator. I see this as an argument in favor of either reusable JSON data and JS-side templating (i.e. all in Vue) or reusable XHTML and after-the-fact event listeners (i.e. all in raw XHTML), not using the servlet as a Vue template source.

Side note: Any time you insert raw HTML into your page, you open the door for XSS; Vue’s templating is meant specifically to handle escaping intelligently. Make sure you trust your external HTML before including it as a template source or opaque HTML blob to render.

Leave a comment