Delivering Vue.js components through JSON payload
by Mihael Haluga, February 25, 2020
Some clever usage of Vue.js and browser features will enable any application to fetch Vue components via API that returns them as JSON objects.
Compile Vue components during runtime
The compiled component object holds the template transformed to render function which then can be assigned to a Vue component configuration object with additional logic to create Vue component. Anywhere in Vue application, this component can be used where its parent will insert it in the place of <component /> placeholder (courtesy of Vue dynamic components).
Transform Vue Single File Components into JSON object
Let's say that this is the component that will be returned by API response:
Here we have a simple form with two inputs and a submit button. Pressing the button will submit the form and send values of the inputs to the browser’s console. This code is presented in a Single File Components style which is usually compiled by webpack, so we need to transform it in such a way that it can be delivered as JSON payload:
(Note: data can be included in the script property but it is separated to enable dynamic additions or manipulations to the state)
(Note: usage of backticks is to make this object more readable but in reality that would be regular escaped strings so all of the browsers can parse them)
Insert JSON Vue component in the Vue application
Above is the code for Wrapper Vue component that will dynamically insert any component returned by the API as JSON payload described in the previous segment of this article. The component receives the payload object as a prop fragment, then compiles the template, assigns the behavior to the component, and finally inserts the component in the application and thus into the DOM.
What makes all of this work (beside Vue framework features) is browser's default DOM API. New script HTML node is appended to the body with text representing Vue configuration object as its innerHTML property. Upon appending the node to the body the browser will parse the script and create new object on window.
After that point the Vue component is assigned to the currentFragmet state in the Wrapper and then it replaces <component /> placeholder component in the DOM.