非单文件组件
多个组件都写在一个html文件中。单文件则为 *.vue
使用组件
- 定义组件
使用 Vue.extend(options) 创建,其中options和之前new Vue中的options大体一致,区别如下:
- 没有el(所有组件由一个vm管理,由vm中的el决定使用哪个容器)
- data必须写成函数式,避免组件被复用时,数据存在引用关系。函数式随时都能最新值。
- 使用 template 可以配置组件结构。
定义组件示例,template中只能有一个根元素:
const school = Vue.extend({
template:`
<div>
<h2> 学校:{{schoolName}}</h2>
<h3> 地址:{{schoolLocation}}</h3>
</div>
`,
data() {
return {
schoolName:'清华大学',
schoolLocation:'北京'
}
},
});
- 注册组件
- 局部注册:new Vue的时候传入components选项。如果key和value值一致,可以简写为key
new Vue({
el:"#root",
data() {
return {
content:'components!'
}
},
// 注册组件
components:{
// 简写为 school
school:school,
// 简写为 student
student:student
}
})
- 全局注册:Vue.component(’组件名’, 组件)
// 全局注册
Vue.component('hello', hello);
- 使用组件
<school></school>
组件名
一个单词组成:
- 第一种写法(首字母小写):school
- 第二种写法(首字母大写):School
多个单词组成:
- 第一种写法(kebab-case命名):my-schoool
- 第二种写法(CamelCase命名):MySchool(需要vue脚手架支持)
备注:
- 组件名尽可能回避html已有的元素名称,例如h2、H2
- 使用name配置项指定组件在开发者工具中的名字。
组件标签
写法:
- <school></school>
- <school />,必须在vue脚手架中使用,否则后续组件无法渲染
简写
const school = Vue.extend(options)
// 简写
const school = options
const student = {
template:`
<div>
姓名:<h2>{{studentName}}</h2>
年龄:<h3>{{studentAge}}</h3>
</div>
`,
data() {
return {
studentName:'wuyuhan',
studentAge:'27'
}
},
};