I'm trying to implement an external template (creating an HTML page), but I can not succeed. This page is a ASP.NET MVC page that contains a Vue app.
I want to move the template section of this component to an external file, but whenever I do this it doesn't work.
The following (below) does work, but it's not easy to maintain or build upon due to loss of text editing features.
Vue.component('my-component', { template: '#my-component' }
This is the current code and it works perfectly:
var foo = Vue.component('foo', {
template:'
<table class="table">
<template v-for="(foo, ColName, index) in foos">
<template v-if="index % 3 == 0">
<tr>
</tr>
</template>
<th>{{ColName}}</th>
<td v-if="foo">{{foo}}</td>
<td v-else> -- </td>
</template>
</table>',
data: function () {
return {
foos: null,
NumColuns: 3
}
},
mounted() {
axios
.get('/api/account/foo/')
.then(response => {
this.foos = response.data
})
.catch(error => {
console.log(error1)
this.errored = true
})
.finally(() => this.loading = false)
}
});
var foo = new Vue({
el: '#foo-vue'
});
To fetch the HTML template from a file you need a async component.
Documentation: https://vuejs.org/v2/guide/components-dynamic-async.html
In your example fetch the HTML and return the promise in the Vue.component factory.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<foo></foo>
</div>
<script>
var foo = Vue.component('foo', () => {
return fetch('/template.html')
.then((response) => response.text())
.then((html) => {
return {
template: html,
data: function () {
return { foos: null, NumColuns: 3 }
},
mounted() {
this.foos = [{ foo: 1, ColName: "A" }];
// axios.get('/api/account/foo/').then(response => {
// this.foos = response.data
// })
// .finally(() => this.loading = false)
}
};
});
});
var foo = new Vue({
el: '#app'
});
</script>
</body>
</html>
template.html
<table class="table">
<template v-for="(foo, ColName, index) in foos">
<template v-if="index % 3 == 0">
<tr>
</tr>
</template>
<th>{{ColName}}</th>
<td v-if="foo">{{foo}}</td>
<td v-else> -- </td>
</template>
</table>
If your view is a razor .cshtml
template then you can just extract your template to a html file and load that file to your ASP.NET MVC view as raw html code since Vue template is valid html:
<!-- in cshtml view -->
<script id="my-component" type="text/x-template">
@Html.Raw(File.ReadAllText(Server.MapPath("~/Path/To/Template/my-component-template.html")))
</script>
And in your Vue component it should work with template: '#my-component'
as you mentioned.
Docs: Vue: Edge Cases
P.S. You can prepare a partial view for your components or create some extension method to make code more readable and add some caching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With