rks*_*ksh 59 javascript jquery angularjs vue.js
我是Vue.js的新手,我已经使用了AngularJS一段时间,而且我们习惯于加载模板,例如,
template: '/sometemplate.html',
controller: 'someCtrl'
Run Code Online (Sandbox Code Playgroud)
我们怎么能在Vue中做这样的事情,而不是像这样在JavaScript中保存大型HTML模板,
new Vue({
el: '#replace',
template: '<p>replaced</p>'
})
Run Code Online (Sandbox Code Playgroud)
对于小模板来说这是可以的,但对于大模板这是否实用?
有没有办法加载外部模板HTML或在像Vue中的脚本标记中使用HTML模板?
<script type="x-template" id="template>HTML template goes here</html>
Run Code Online (Sandbox Code Playgroud)
Bil*_*ell 28
您可以通过引用它来使用脚本标记模板id.
{
template: '#some-id'
}
Run Code Online (Sandbox Code Playgroud)
虽然,我强烈建议使用vueify(如果你使用browserify)或vue-loader(如果你使用webpack),这样你就可以将你的组件存储在.vue像这样的漂亮的小文件中.
此外,Vue的作者写了一篇关于外部模板网址主题的好文章:
http://vuejs.org/2015/10/28/why-no-template-url/
Fra*_*ger 14
你可以尝试这个:https: //github.com/FranckFreiburger/http-vue-loader
例:
new Vue({
components: {
'my-component': httpVueLoader('my-component.vue')
},
...
Run Code Online (Sandbox Code Playgroud)
swi*_*ift 11
大卫,这是一个很好的例子,但是确保编译DOM的最佳方法是什么?
https://jsfiddle.net/q7xcbuxd/35/
当我模拟异步操作时,就像上面的例子一样,它可以工作.但是,只要我"动态"加载外部页面,Vue就会抱怨,因为DOM尚未就绪.更具体地说:
有没有比在页面加载时调用更好的方法呢?我试过了,但这没有帮助.Uncaught TypeError: Cannot set property 'vue' of undefined$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
});
});
});
Run Code Online (Sandbox Code Playgroud)
在实际的模板中,我删除了
<script id="someTemplate" type="text/x-template"></script>
Run Code Online (Sandbox Code Playgroud)
标签,只包含html.
(此解决方案需要来自https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.10/vue-resource.min.js的http加载程序)
小智 5
我试过http-vue-loader,它工作正常。这个库很容易使用并且有很好的文档和例子
尽管您不能直接从文件中加载模板,但您仍然可以将 html 保存在单独的单文件组件中。你甚至可以跳过<script>...</script>部分。
my-component.vue
<template>
<div class="hello">Hello {{who}}</div>
</template>
Run Code Online (Sandbox Code Playgroud)
index.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>
Run Code Online (Sandbox Code Playgroud)
两个文件应该放在同一个文件夹中
您可以将此方法与 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]);
});
Run Code Online (Sandbox Code Playgroud)
只需将<script>基于标签的模板放在something.html服务器上即可。
如果您使用 jQuery,.load应该可以工作。
只需确保在 Vue 编译相关 DOM 之前完成此操作即可。或者使用$mount手动设置。
| 归档时间: |
|
| 查看次数: |
73446 次 |
| 最近记录: |