vue组件

本文介绍了Vue.js组件的基础概念,包括组件复用、模板扩展和注册方法。详细讲解了全局和局部注册步骤,并强调了父子组件的正确用法,以及如何通过props进行数据传递。还涉及了组件注册的语法糖和使用script或template标签的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:https://www.cnblogs.com/goloving/p/8630603.html

组件基础

  1. 组件是可复用的 Vue 实例。
  2. 组件可以扩展HTML元素,封装可重用的HTML代码,我们可以将组件看作自定义的HTML元素。
  3. 因为组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。
  4. 一个组件的 data 选项必须是一个函数
  5. 每个组件必须只有一个根元素
  6. 为了能在模板中使用,组件必须先注册以便 Vue 能够识别。
    有两种组件的注册类型:全局注册和局部注册。

组件的创建和注册基本步骤

Vue.js的组件的使用有3个步骤:创建组件构造器、注册组件和使用组件。

在这里插入图片描述

  1. 全局注册

    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    	<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    </head>
    <body>
    	<div id="app">
        	<!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
        	<my-component></my-component>
     	</div>
    	<script>
        	// 1.创建一个组件构造器
        	var myComponent = Vue.extend({
            	template: '<h1>This is my first component!</h1>'
        	})
        
        	// 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component>
        	Vue.component('my-component', myComponent)
        
        	new Vue({
            	el: '#app'
       	 	});
        
    	</script>
    </body>
    </html>
    
  2. 局部注册

    // 1.创建一个组件构造器
    var myComponent = Vue.extend({
    	template: '<div>This is my first component!</div>'
    })
    
    new Vue({
    	el: '#app',
    	components: {
        	// 2. 将myComponent组件注册到Vue实例下
        	'my-component' : myComponent
    	}
    });
    

    该局部组件只能在app下才能起作用

父组件和子组件

在组件中定义并使用其他组件,这就构成了父子组件的关系。
在这里插入图片描述

子组件只能在父组件的template中使用。
注意下面两种子组件的使用方式是错误的:
1、以子标签的形式在父组件中使用
2、在父组件标签外使用子组件

组件注册语法糖

  1. 使用Vue.component()直接创建和全局注册组件:

    // 全局注册,my-component是标签名称,后面跟模板template
    Vue.component('my-component',{
    	template: '<div>This is the first component!</div>'
    })
    

    相当于把Vue.extend()直接放入第二个参数

  2. 在选项对象的components属性中实现局部注册:

    var vm = new Vue({
    	el: '#app',
    	components: {
        	// 局部注册,my-component2是标签名称
        	'my-component2': {
            	template: '<div>This is the second component!</div>'
        	},
        	// 局部注册,my-component3是标签名称
        	'my-component3': {
            	template: '<div>This is the third component!</div>'
        	}
    	}
    })
    

使用script或template标签

在这里插入图片描述
在这里插入图片描述

父子组件通讯

组件实例的作用域是孤立的。

父传子

这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件
在这里插入图片描述
在这里插入图片描述

prop默认是单向绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。这是为了防止子组件无意修改了父组件的状态。
如果需要,可以使用.sync显式地指定双向绑定,这使得子组件的数据修改会回传给父组件。

<my-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></my-component>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不知-_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值