Vue中组件到底是什么

1.先说结论:

Vue中组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。

2.我们使用组件时发生了什么?
比如定义了一个school,然后在页面上使用它
我们只需要写 < school/ > 或< school >< /school>,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的:new VueComponent(options)。

3.实际代码,我们定义一个school组件,然后在页面中打印出来。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>VueComponent</title>
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<div id="root">
			<school></school>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false
		
		//定义school组件
		const school = Vue.extend({
    
    
			name:'school',
			template:`
				<div>
					<h2>学校名称:{
     
     {name}}</h2>	
					<h2>学校地址:{
     
     {address}}</h2>	
					<button @click="showName">点我提示学校名</button>
				</div>
			`,
			data(){
    
    
				return {
    
    
					name:'尚硅谷',
					address:'北京'
				}
			},
			methods: {
    
    
				showName(){
    
    
					console.log('showName',this)
				}
			},
		})
		const test = Vue.extend({
    
    
			template:`<span>atguigu</span>`
		})
	    console.log('@',school)
		//创建vm
		const vm = new Vue({
    
    
			el:'#root',
			components:{
    
    school,hello}
		})
	</script>
</html>

打印结果如下,是一个VueComponent构造函数:
在这里插入图片描述
我们也可以点进去看一下源码

在这里插入图片描述
我们使用组件时如何证明它执行了new VueComponent()操作?
我们直接在源码中加一句代码:
在这里插入图片描述
首先我们在代码中只定义组件,并不使用。页面中只有打印出school,相当于前面说的school组件本质是个VueComponent构造函数,但是并未执行。
在这里插入图片描述
然后我们在页面中使用school组件,打印结果如下:

在这里插入图片描述
4.vm(Vue实例)和组件的关系,我们直接打印vm。

console.log(vm);

在这里插入图片描述
我们发现有个chilren属性,是个数组,展开之后发现是school对应的VueComponent实例对象
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/129480307