在组件template内容很冗长、复杂的情况下,如果在Javascript中拼接字符串,代码的可读性,以及编码效率都是很低的。Vue提供了另外一种定义模板的方式,在<script>标签中使用text/x-template类型,并且指定一个id,将这个id赋给template:
<!-- x-template -->
<body>
<div id="app">
<my-component></my-component>
<!-- 使用x-template -->
<script type="text/x-template" id="my-component">
<div>这是组件的内容</div>
</script>
</div>
<script src = "https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
Vue.component('my-component', {
template: '#my-component' //将id赋给template
});
var app = new Vue({
el: '#app',
})
</script>
</body>
这种方法将模板和组件的其他定义隔离了,Vue不建议滥用。如果使用编译工具来编译.vue文件后,就可以更好的解决HTML书写的问题。
参考
- 《Vue.js 实战》
Vue.js 中的x-template用法解析
Vue在组件内容复杂时提供了一种x-template定义模板的方法,通过在script标签中指定id,提高代码可读性和编码效率。这种方式将模板与组件其他定义分离,但Vue并不推荐过度使用。在使用编译工具处理后,可以更好地处理HTML编写问题。
140

被折叠的 条评论
为什么被折叠?



