Created
December 6, 2018 22:28
-
-
Save funkatron/4718f93c0245d1243399ac4f0aa0c868 to your computer and use it in GitHub Desktop.
Simple JS function to dynamically load an HTML template for a VueJS component via AJAX
This file contains 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
/** | |
* Registers a Vue component. Can take a `templateUrl` in the componentDef that is loaded and resolved to `template` | |
* @param {string} name | |
* @param {Object} componentDef | |
*/ | |
function registerVueComponent(name, componentDef) { | |
if (componentDef.templateUrl) { | |
Vue.component(name, function (resolve, reject) { | |
// retrieve the template via axios async call | |
axios.get(componentDef.templateUrl) | |
.then(function (response) { | |
// set the response.data to the component template | |
componentDef.template = response.data; | |
// delete the templateUrl property entirely | |
delete componentDef.templateUrl; | |
// resolve the promise and init the component | |
resolve(componentDef); | |
}) | |
.catch(function (error) { | |
alert('Problem loading component'); | |
reject(error); | |
}); | |
}); | |
} else { // if no templateUrl, just register normally | |
Vue.component(name, componentDef); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment