Javascript VueJs模板。如何加载外部模板

Javascript VueJs模板。如何加载外部模板,javascript,jquery,angularjs,vue.js,Javascript,Jquery,Angularjs,Vue.js,我是Vue.js的新手,我使用AngularJS已经有一段时间了,在AngularJS中,我们用来加载模板,例如 template: '/sometemplate.html', controller: 'someCtrl' 我们如何在Vue中做这样的事情,而不是像这样将大型HTML模板保存在JavaScript中 new Vue({ el: '#replace', template: '<p>replaced</p>' }) newvue({ el:“#替换”

我是Vue.js的新手,我使用AngularJS已经有一段时间了,在AngularJS中,我们用来加载模板,例如

template: '/sometemplate.html',
controller: 'someCtrl'
我们如何在Vue中做这样的事情,而不是像这样将大型HTML模板保存在JavaScript中

new Vue({
  el: '#replace',
  template: '<p>replaced</p>'
})
newvue({
el:“#替换”,
模板:“已替换”
})
这对于小模板来说是可以的,但是对于大模板来说,这是实用的吗

是否有一种方法可以加载外部模板HTML或在脚本标记中使用HTML模板,如在Vue中

<script type="x-template" id="template>HTML template goes here</html>

您可以将此方法用于superagent:

var promise = superagent.get("something.html")
    .end(function (error, response) {
        if (error) {
            console.error("load of something.html failed", error));
            return;
        }

        var parser = new DOMParser()
        var doc = parser.parseFromString(response.text, "text/html");
        document.body.appendChild(doc.scripts[0]);
    });
只需将基于标签的模板放入服务器上的
something.html
中即可

如果您使用的是jQuery,那么它应该可以工作


只需确保在Vue编译相关DOM之前完成此操作。或者使用手动设置。

David,这是一个很好的示例,但是确保编译DOM的最佳方法是什么

当我模拟一个异步操作时,就像上面的例子一样,它是有效的。但是,当我“动态”加载外部页面时,Vue就会抱怨,因为DOM还没有准备好。 更具体地说:
未捕获类型错误:无法设置未定义的属性“vue
有没有比加载页面时调用
$compile
更好的方法?我试过使用
$mount
,但没有效果

更新: 没关系,我终于想出了办法:

Vue.component('async-component', function (resolve, reject) {
    vue.$http.get('async-component.html', function(data, status, request){
        var parser = new DOMParser();
        var doc = parser.parseFromString(data, "text/html");
        resolve({
            template: doc
        });
    });
});
在实际的模板中,我删除了

<script id="someTemplate" type="text/x-template"></script>

标签,并且只包含html


(此解决方案需要来自的http加载程序)

使用browserify捆绑所有内容,如下所示:

//Home.js

import Vue from 'vue';

var Home = Vue.extend({
    template: require('./Home.vue')
});

export default Home;

//Home.vue
<h1>Hello</h1>

// And for your browserify bundle use a transform called stringify

... .transform(stringify(['.html', '.svg', '.vue', '.template', '.tmpl']));
//Home.js
从“Vue”导入Vue;
var Home=Vue.extend({
模板:require(“./Home.vue”)
});
导出默认主页;
//Home.vue
你好
//对于browserify包,使用名为stringify的转换
... .转换(stringify(['.html'、'.svg'、'.vue'、'.template'、'.tmpl']);

您可以通过引用脚本标记模板的
id
来使用脚本标记模板

{
  template: '#some-id'
}
不过,我强烈建议您使用(如果您使用browserify)或(如果您使用webpack),这样您就可以将组件存储在类似这样的漂亮的小
.vue
文件中

此外,Vue的作者还写了一篇关于外部模板URL主题的文章:

你可以试试这个:
对于Vue2:
对于Vue3:

示例(Vue2):

 new Vue({
        components: {
            'my-component': httpVueLoader('my-component.vue')
        },
        ...
Vue.createApp({
  components: {
    'my-component': Vue.defineAsyncComponent(() => loadModule('./myComponent.vue', opts))
  },
  ...
示例(Vue3):

 new Vue({
        components: {
            'my-component': httpVueLoader('my-component.vue')
        },
        ...
Vue.createApp({
  components: {
    'my-component': Vue.defineAsyncComponent(() => loadModule('./myComponent.vue', opts))
  },
  ...
1.在Vue 2.x中,我建议使用.Vue文件来遵守惯例,但要颠倒导入顺序: 然后在组件注册中

import helloworld from './helloworld/template.vue'

new Vue({
 components: {
 'helloworld': helloworld
},
...})
通过这种方式,您可以两全其美,不必强迫自己在字符串中构建模板

2.如果您想延迟加载,显然在VUE2.x中有一种方法可以做到这一点 这将根据浏览器中该页面的请求加载helloworld.js(其中将包含该组件的所有代码)

当然,以上所有内容都假设您使用的ES6具有
导入
功能

我已经尝试过了,效果很好。 该库易于使用,具有良好的文档和

虽然不能直接从文件加载模板,但仍然可以将html保存在单独的单个文件组件中。您甚至可以跳过
部分

用法(来自装载机文档)
my component.vue

<template>
    <div class="hello">Hello {{who}}</div>
</template>

两个文件应放在同一级别的一个文件夹中

至少有两种方法可以实现您想要的内容,Bill Criswell已经提到了其中一种(x模板),但我认为值得添加一个示例

  • 像这样定义组件

    Vue.component('my-checkbox'{
    //x模板的id
    模板:“#我的模板”
    });

  • 使用x模板添加html文件(id应与组件中指定的id匹配)

  • 另一种方法(我更喜欢这种方法)是使用内联模板

  • 像这样定义模板

    Vue.component('my-template',{})

  • 添加包含组件和模板的html文件

    放置html的位置

  • <!doctype html>
    <html lang="en">
      <head>
        <script src="https://unpkg.com/vue"></script>
        <script src="https://unpkg.com/http-vue-loader"></script>
      </head>
    
      <body>
        <div id="my-app">
          <my-component></my-component>
        </div>
    
        <script type="text/javascript">
          new Vue({
            el: '#my-app',
            components: {
              'my-component': httpVueLoader('my-component.vue')
            }
          });
        </script>
      </body>
    </html>
    

    只是别忘了添加
    内联模板
    属性,否则它将不起作用

    您可以将模板的语言设置为Slim或Haml之类的语言,就像您可以在
    元素中设置
    lang='sass'
    一样吗?如果是这样的话,是否还有其他依赖项可以让Transfilation工作?回答了我自己的问题。支持的引擎是博客文章中唯一有价值的论据,是关于请求数量的论据。其余的都是意见和废话。是否使用.vue来突出显示正确的语法?在使用.vue文件之前,我已经有了正确的语法突出显示。“为什么没有模板url”中的要点是否基本上使微型前端不可能实现?@NicuSurdu实际上这正是Angular如此臃肿和沉重的原因。我同意这对开发人员来说比较容易,但是客户端会遭受很多麻烦。这真是一个麻烦……Vue文档中描述“异步组件”的部分,它可以实现延迟加载:浏览器中默认启用ES6吗?如果没有,我该如何启用它?@saidfagan如您所见:最新版本的Chrome、Firefox和Safari支持超过90%的ES6功能,最新版本的Microsoft Edge也相当不错。如果担心的话,IE11将是“相关浏览器”支持的落后者。不管是哪种方式,如果您想确保始终可以使用Babel这样的transpiler来构建与香草兼容的Javascript,那正是我要做的,谢谢您的回答。不幸的是,不建议在生产中使用。看起来使用
    npm
    webpack
    是唯一的选择……是推荐的选择,而不是唯一的选择好吧,如果你,作为这个插件的创建者,这么认为的话,我会尝试一下。
    <!doctype html>
    <html lang="en">
      <head>
        <script src="https://unpkg.com/vue"></script>
        <script src="https://unpkg.com/http-vue-loader"></script>
      </head>
    
      <body>
        <div id="my-app">
          <my-component></my-component>
        </div>
    
        <script type="text/javascript">
          new Vue({
            el: '#my-app',
            components: {
              'my-component': httpVueLoader('my-component.vue')
            }
          });
        </script>
      </body>
    </html>