通过组件,可以很方便地实现页面复用,减少重复页面的创建,减少重复代码。一个页面可以引入多个组件。下面介绍在HBuilder X中创建组件的方法:
一.组件的创建
1.选中项目,右键-->新建目录(文件夹),并将文件夹命名为components;
2.选中components,右键,新建组件,注意,目录名必须命名为components,右键选项才会有新建组件选项


组件命名有两种方式:1.驼峰式命名:UserInfo;2.短横给连接式命名:user-info;
在UserInfo/User-info.vue添加如下代码:
<template>
	<view>
		<image src="/static/logo.png" mode=""></image>
		<view class="username">Jim</view>
	</view>
</template>注意:组件里的页面不能直接访问,需要主页面中引入组件的方式来读取组件里页面的内容
二.组件的使用
<template>
	<view>
		<image src="/static/logo.png" mode=""></image>
		<view class="username">Jim</view>
	</view>
</template>
<script setup>
	
</script>
<style lang="scss" scoped>
</style>在上面组件中,style中使用了scoped,起的作用是style里的css样式仅作用于本组件,不会污染其他组件。
效果:




















