了解组件:
问题一:了解什么是组件?
=>组件的定义:实现应用中局部功能代码和资源的集合
问题二:组件化编程和传统编程的相比之下的优势?
=>优势:复用编码,简化项目编码,提高运行效率
非单文件组件:
<script src="../js/vue.js"></script>
<div id="root">
<h1>{{ msg }}</h1>
<hr>
<hello></hello>
<hr>
<!-- 第三步:编写组件标签 -->
<school></school>
<hr>
<!-- 第三步:编写组件标签 -->
<student></student>
</div>
<div id="root2">
<hello></hello>
</div>
<script>
Vue.config.productionTip = false
// 第一步:创建school组件
const school = Vue.extend({
template:`
<div>
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="showName">点击提示学校名称</button>
</div>
`,
data(){
return {
schoolName: '清华大学',
address: '中国北京'
}
},
methods:{
showName(){
alert(this.schoolName)
}
}
})
// 第一步:创建student组件
const student = Vue.extend({
template:`
<div>
<h2>学生名称:{{studentName}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
data(){
return {
studentName: '陈慕夏',
age: 16
}
}
})
// 第一步:创建hello组件
const hello = Vue.extend({
template:`
<div>
<h2>你好啊!{{name}}</h2>
</div>
`,
data(){
return {
name: '陈慕夏'
}
}
})
// 第二步:全局注册组件
Vue.component('hello',hello)
//参数一'hello' :组件名
//参数二:hello :组件位置(组件在哪)
//创建VM
new Vue({
el:'#root',
data:{
msg: '欢迎来到清华大学'
},
// 第二步:注册组件 (局部注册)
components:{
//components里配置的一组一组的key:value都是组件名
//定义组件时所写的const school/const student并不是最后的组件名,只是一个中转变量
//components里配置的key值才是组件名,定义组件时的变量 const school和components里的组件名school一致,方便简写
//简写:school 不简写:school:school
school,
student
}
})
</script>
总结:
-
Vue中使用组件的三大步骤:
-1. 定义组件(创建组件)
-2. 注册组件
-3. 使用组件 (编写组件标签) -
1.如何定一个组件:
使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别:
区别如下:
-1. el不要写,为什么? ------ 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器
-2. data必须写成函数,为什么? ------ 避免组件被复用时,数据存在引用关系
备注: 使用template可以配置组件结构 -
2.如何注册组件:
-1. 局部注册:靠new Vue的时候传入components选项
-2. 全局注册:靠Vue.component(‘组件名’, 组件) -
3.编写组件标签:
注意点:
- 关于组件名:
1. 一个单词组成:
- 第一种写法:首字母小写 -------- school
- 第二种写法:首字母大写 -------- School
2. 多个单词组成:
- 第一种写法:kebab-case命名 ------ my-school
- 第二种写法:CamelCase命名 ------ MySchool (需Vue脚手架支持)
备注: - 组件名尽可能回避HTML中已有的元素名称,例如:h1,h2,H2都不行 - 可以使用name配置项指定组件在开发者工具中呈现的名字
- 关于组件标签:
- 第一种写法:
- 第二种写法:
备注: - 不使用脚手架时,第二种写法<school/>会导致后续组件不能渲染
- 一个简写形式:
- const school = Vue.extend(options) ------ 简写: const school = options