Created
November 6, 2017 22:58
-
-
Save padcom/8e36c7df3d7268470c9b3067f928075a to your computer and use it in GitHub Desktop.
VueJS 2 component for dynamically compiling template passed on in props
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Vue from 'vue' | |
| import { compileToFunctions } from 'vue-template-compiler' | |
| // Here we define a DynamicContent component that will serve as wrapper | |
| // for the body that will actually be "dynamic" | |
| const DynamicContent = Vue.extend({ | |
| template: '<DynamicContentBody :template="template" :data="data" />', | |
| // There are 2 required properties for this component to work | |
| props: { | |
| template: { required: true, type: String }, // this is the actual template that will be rendered | |
| data: { required: true, type: Object }, // this is the data object containing values for the template | |
| }, | |
| created() { | |
| // We are using the "created" callback to dynamically register a new component | |
| // called "DynamicContentBody" that will render the dynamic content | |
| this.$options.components.DynamicContentBody = { | |
| props: { | |
| data: { required: true, type: Object } | |
| }, | |
| render: compileToFunctions(this.$options.propsData.template).render | |
| } | |
| } | |
| }) | |
| window.app = new Vue({ | |
| el: '#app', | |
| template: '<DynamicContent :template="tmpl" :data="myData" />', | |
| data: { | |
| // In this template :data passed on to the DynamicContent component | |
| // can be referenced using the "data" property | |
| tmpl: '<span>This is: {{data.field1}} - {{data.field2}} !!!</span>', | |
| // This is an object containing data to be rendered | |
| myData: { | |
| field1: 'X', | |
| field2: 'Y', | |
| } | |
| }, | |
| components: { | |
| DynamicContent | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment