模块
- 理解: 向外提供特定功能的js程序,一般就是一个js文件
- 为什么: js文件很多很复杂
- 作用: 复用js,简化js编写,提高js运行效率
组件
- 理解: 用来实现局部(特定)功能效果的代码集合(html/css/js/image)
- 为什么: 一个界面的功能很复杂
- 作用: 复用编码,简化醒目编码,提高运行效率
使用组件的三大步骤:
- 定义组件(创建组件)
使用Vue.extend(options)创建,其中options和new Vue(options)传入的options几乎一样,区别如下:
(1)不需要写el绑定,最终所有的组件都要经过一个vm的管理,由vm中的el决定服务于哪个容器
(2)data必须写成函数,避免组件在复用时,数据存在引用关系 - 注册组件
(1)局部注册: new Vue时传入components 和 filter同理
(2)全局注册: Vue.component('组件名', 组建) - 使用组件(写组件标签)
代码如下:
<body>
<div class="app">
<!-- 使用school组件 -->
<school></school>
<!-- 使用student组件 -->
<student></student>
</div>
<script>
// 创建Vue组件
//创建school组件
const school = Vue.extend({
template: `
<div>
<h2>学校的名称是:{{schoolName}}</h2>
<h2>学校的地址是:{{address}}</h2>
</div>
`,
data() {
return {
schoolName: '北京大学',
address: '北京',
}
},
})
//创建student组件
const student = Vue.extend({
//使用template创建模板
template: `
<div>
<h2>学生的名称是:{{studentName}}</h2>
<h2>学生的年龄是:{{age}}</h2>
</div>
`,
data() {
return {
studentName: '张三',
age: 18,
}
},
})
// 全局注册组件
Vue.component('student', student)
new Vue({
el: '.app',
// Vue实例内部注册组件
components: {
//key 和 value 相同时,可以简写,完整写法:'school': school
school
},
})
</script>
</body>
组件注意事项
- 关于组件名:
1.1 一个单词组成:
(1)首字母小写 例如school
(2)首字母大写 例如School
1.2 多个单词组成:
(1)kebab-case命名:my-school, 需要用''声明为字符串
(2)CamelCase命名: MySchool - 关于组件标签
2.1 完整写法<school></school>
2.2 单标签写法<school/>
需要在Vue脚手架下使用,html文档中使用会有问题,导致后续组件不能渲染 - 创建组件的简写方式:
const school = Vue.extend(options)
可以简写为:const school = options