首页 > 解决方案 > 使用 .NET (MVC) 的模板实现 (VUE) 问题

问题描述

我正在尝试实现一个外部模板(创建一个 HTML 页面),但我无法成功。此页面是包含 Vue 应用程序的 ASP.NET MVC 页面。

我想将此组件的模板部分移动到外部文件,但每当我这样做时,它都不起作用。

以下(下)确实有效,但由于失去了文本编辑功能,维护或建立起来并不容易。

Vue.component('my-component', { 模板:'#my-component' }

这是当前的代码,它完美地工作:

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' 
});

标签: javascriptasp.net-mvcvue.js

解决方案


要从文件中获取 HTML 模板,您需要一个异步组件。

文档:https ://vuejs.org/v2/guide/components-dynamic-async.html

在您的示例中,获取 HTML 并返回 Vue.component 工厂中的承诺。

<!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>

模板.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>

推荐阅读