Skip to content

Instantly share code, notes, and snippets.

@westc
Last active November 27, 2022 12:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/feb8dce2152263333c2e9231b5946caa to your computer and use it in GitHub Desktop.
Save westc/feb8dce2152263333c2e9231b5946caa to your computer and use it in GitHub Desktop.
Takes an HTML string with Vue.js syntax and converts it to a normal HTML string.
function vueToHTML(vueHTML, data, onRender) {
function onUpdated() {
this.$nextTick(function () {
onRender(this.$el.innerHTML);
});
}
return new Vue({
template: '<div>' + vueHTML + '</div>',
el: document.createElement('div'),
data: Object(data),
mounted: onUpdated,
updated: onUpdated
});
}

vueToHTML(…)

This function can be used to take an HTML string containing Vue Syntax and convert it to a regular HTML string.

Parameters

  1. vueHTML string

    The HTML string containing Vue Syntax that is to be converted to a regular HTML string.

  2. data Object|null

    The data object that can be referenced in order to render vueHTML with the specified data. If null is given a blank object will be used as the data source.

  3. onRender function(html)

    The callback function to be called with the resulting rendered HTML string. This is called 1st when the function is called and vueHTML is rendered. It is also called if data is changed thusly triggering an update of the rendered HTML.

Returns

The Vue instance that is used to render the desired HTML.

Example run:

vueToHTML(
  '<div v-for="a in [1,2,3]">{{a}}</div>',
  null,
  function(output) {
    console.log('Output:', output);
  }
);

Another example run:

vueToHTML(
  '<div v-for="a in arr">{{a}}</div>',
  { arr: [9,8,7,6,5,4,3,2,1] },
  function (output) {
    console.log('Output:', output);
  }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment