Last active
December 13, 2019 21:20
-
-
Save james2doyle/3c21881d5d360e7b042acecbe9761b25 to your computer and use it in GitHub Desktop.
A Vue component that emulates the features of ng-include from Angular v1.x
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
import Vue from 'vue'; | |
import axios from 'axios'; | |
const AsyncTemplateComponent = Vue.component('async-template', function(resolve) { | |
resolve({ | |
name: 'async-template', | |
props: { | |
url: { | |
type: String, | |
required: true, | |
}, | |
}, | |
data() { | |
return { | |
// might show depending on how the loading goes - we are using a Loading component below | |
template: '<div class="loading">Loading...</div>', | |
} | |
}, | |
mounted() { | |
axios.get(this.url, { | |
params: this.params || null, | |
headers: { | |
'Accept': 'text/html', | |
}, | |
}) | |
.then(({ data }) => { | |
// updating the data triggers a render | |
this.template = data; | |
}); | |
}, | |
render(createElement) { | |
// create a wrapper for the response HTML | |
const compiledTemplate = Vue.compile(`<div | |
class="async-template" | |
data-url="${this.url}" | |
v-html="template"></div>`); | |
// return the rendered template and use this component as the invoker | |
return compiledTemplate.render.call(this, createElement); | |
}, | |
}); | |
}); | |
const AsyncTemplate = () => ({ | |
component: AsyncTemplateComponent, | |
// A component to use while the async component is loading | |
loading: import('Components/Loading.vue'), | |
// A component to use if the component fails to load or has a fatal error | |
error: import('Components/Error.vue'), | |
}) | |
export default AsyncTemplate; |
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
<!-- templateUrl = https://example.com/markup.html --> | |
<!-- This: --> | |
<async-template :url="templateUrl"></async-template> | |
<!-- Will be replace with: --> | |
<div class="async-template" data-url="https://example.com/markup.html"> | |
<!-- eval'd contents of https://example.com/markup.html --> | |
<!-- https://example.com/markup.html can be a Vue template --> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment