Vue 组件6内联模板

时间:2023-03-09 13:31:25
Vue 组件6内联模板

如果子组件有inline-template特性,组件将把它的内容当做模板,而不是把它当做分发内容,这样模板更灵活。

<my-component inline-template>
<div>
<p>These are compiled as the component's own template.</p>
<p>Not parent's transclusion content.</p>
</div>
</my-component>
但是,inline-template让模板的作用域难以理解,最佳实践是使用template选项在组件内定义模板或者在.vue文件中使用template元素。
X-templates
另一种定义模版的方式是在 JavaScript 标签里使用 text/x-template 类型,并且指定一个 id。例如:
<script type="text/x-template" id="hello-world-template">
<p>Hello hello hello</p>
</script>
Vue.component('hello-world', {
template: '#hello-world-template'
})
这在有很多模版或者小的应用中有用,否则应该避免使用,因为它将模版和组件的其他定义隔离了。
对低开销的静态组件使用v-once
尽管在vue中渲染html非常快很快,不过当组件中包含大量静态内容时,可以考虑使用v-once,将渲染结果缓存起来,就像:
Vue.component('terms-of-service', {
template: '\
<div v-once>\
<h1>Terms of Service</h1>\
... a lot of static content ...\
</div>\
'
})