组件化回顾
- 一个Vue组件就是一个拥有预定义选项的一个Vue实例
- 一个组件可以组成页面上一个功能完备的区域,组件可以包含脚本,样式,模板
组件注册
组件注册方式
全局组件
- 方法Vue.component()
- 我们首先来观察Vue.component()的实现
- 我们再观察initAssetRegisters函数的实现
- 我们再重点观察this.options._base.extend(definition)的实现方式,也就是Vue.extend()
- 在Vue.component()中,第二个参数如果传递的是对象的话,它内部会调用Vue.extend()方法,把该组件的选项对象转化为Vue构造函数的子类,所以我们经常会说组件其实也是一个Vue实例
小结:Vue.component()就是基于传入的选项对象创建了组件的构造函数Sub,组件的构造函数继承自Vue构造函数Super,所以组件对象(Sub构造函数的实例)拥有和Vue实例一样的成员
局部组件
调试组件注册的过程
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue.component</title>
</head>
<body>
<div id="app"></div>
<!-- 完成版本 -->
<script src="../../dist/vue.js"></script>
<script>
const Comp = Vue.component("comp", {
template: "<div>Hello Component</div>",
});
const vm = new Vue({
el: "#app",
render() {
return h(Comp);
},
});
// 编译生成的render函数
console.log(vm.$options.render);
</script>
</body>
</html>
- 进入调试
组件的创建过程
回顾首次渲染过程
- Vue构造函数
- this.init()
- this.$mount()
- mountComponent()
- new Warcher()渲染Watcher
- updateComponent()
- vm._render()=>createElement()
- vm._update()