</div>
`,
components: {
'header-content': headerContent,
'header-title': headerTitle
}
};
// 创建实例
new Vue({
el: '#example',
components: {
'my-component': header
}
})
</script>
对于大型应用来说,有必要将整个应用程序划分为组件,以使开发可管理。一般地组件应用模板如下所示
<div id="app">
<app-nav></app-nav>
<app-view>
<app-sidebar></app-sidebar>
<app-content></app-content>
</app-view>
</div>v-once
尽管在 Vue 中渲染 HTML 很快,不过当组件中包含大量静态内容时,可以考虑使用 v-once 将渲染结果缓存起来
Vue.component('my-component', {
template: '<div v-once>hello world!...</div>'
})
Vue组件的模板分离
在组件注册中,使用template选项中拼接HTML元素比较麻烦,这也导致了HTML和JS的高耦合性。庆幸的是,Vue.js提供了两种方式将定义在JS中的HTML模板分离出来
script
在script标签里使用 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'
})上面的代码等价于
Vue.component('hello-world', {
template: '<p>Hello hello hello</p>'
})下面是一个简单示例
<div id="example">
<my-component></my-component>
</div>
<script type="text/x-template" id="hello-world-template">
<div>hello world!</div>
</script>
<script>
Vue.component('my-component', {
template: '#hello-world-template'
})
new Vue({
el: '#example'
})
</script>template
如果使用<template>标签,则不需要指定type属性
<div id="example">
<my-component></my-component>
</div>
<template id="hello-world-template">
<div>hello world!</div>
</template>
<script>
// 注册
Vue.component('my-component', {
template: '#hello-world-template'
})
// 创建根实例
new Vue({
el: '#example'
})
</script>
Vue组件的命名约定
对于组件的命名,W3C规范是字母小写且包含一个中划线(-),虽然Vue没有强制要求,但最好遵循规范










