我正在尝试实现一个外部模板(创建一个 HTML 页面),但我无法成功。此页面是包含 Vue 应用程序的 ASP.NET MVC 页面。
我想将此组件的模板部分移动到外部文件,但无论何时我这样做都不起作用。
以下(下方)确实有效,但由于缺少文本编辑功能,因此不容易维护或构建。
Vue.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'
});
最佳答案
要从文件中获取 HTML 模板,您需要一个异步组件。
文档:https://v2.vuejs.org/v2/guide/components-dynamic-async.html
在您的示例中,获取 HTML 并在 Vue.component 工厂中返回 promise 。
<!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>
关于javascript - 使用 .NET (MVC) 的模板实现 (VUE) 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811534/