Problem with template implementation (VUE) using .NET (MVC) Problem with template implementation (VUE) using .NET (MVC) vue.js vue.js

Problem with template implementation (VUE) using .NET (MVC)


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.


The best thing you can do is configure an entire Vue project, so you can use .vue template files. I recently found an article that explains in detail how to achieve this, but it's specifically aimed at browser extensions. The steps you have to undertake to achieve it, in this case, are identical for the most part, so I'll just link the article here anyway: https://medium.com/javascript-in-plain-english/how-i-built-a-browser-extension-with-vue-part-2-2c4ab2dd752d.

Basically what's happening is, you'll configure the Vue project yourself with Webpack to compile the Vue files into one app.js file, which you'll then reference in your file (in the tutorial this file is his app.html). It will then inject its components into the #app element and handle all virtual DOM manipulations.