从文件加载组件模板

Loading component template from file

将组件模板作为内联 HTML 对我来说不是很容易维护,所以我想从文件中加载它。经过一些谷歌搜索后,我似乎必须使用 DOMParser() 来解析 HTML 文件并将其结果放入模板 属性.

我找到了 following (old) post 并尝试做同样的事情,但是失败了 TypeError: vm.$options.template.charAt is not a function.

这是我目前所拥有的(使用 vue-resource):

main.js

var asyncComponent = Vue.component('async-component', function (resolve, reject) {
    app.$http.get('./template.html', function(data, status, request){
        var parser = new DOMParser();
        var doc = parser.parseFromString(data, "text/html");
        resolve({
            template: doc
        });
    });
});

const router = new VueRouter({
    routes: [
        { path: '/async', component: asyncComponent }
    ]
})

const app = new Vue({
    el: '#app',
    router
});

看到 vue-resource 不再维护了,我也尝试使用 fetch,但是这产生了完全相同的错误:

var asyncComponent = Vue.component('asyncComponent', function (resolve, reject) {
    fetch('./module.html')
    .then(response => response.text())
    .then(function(data) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(data, "text/html");
        resolve({
            template: doc
        });
    });
});

如何使用本机功能从单独的 HTML 文件加载模板,而不必使用 webpack?

template 字段应包含原始 HTML 字符串(不需要 DOMParser)。

使用vue-resource:

app.$http.get('./template.html', function(data, status, request) {
  resolve({
    template: data
  });
});

使用axios:

axios.get('./template.html').then(({ data }) => {
  resolve({
    template: data
  }
});

demo