uniapp组件
uniapp 组件的基本概念
uniapp 的组件是基于 Vue.js 的单文件组件(.vue 文件),支持跨平台开发。组件分为内置组件(如 view、button)和自定义组件,可通过标签直接调用。
内置组件的使用
uniapp 提供了一系列跨平台的内置组件,例如:
view:类似 HTML 的div,用于布局容器。text:文本组件,支持嵌套和样式继承。button:按钮组件,开放能力如微信登录、分享等。
示例代码:
<view class="container">
<text>Hello uniapp</text>
<button @click="handleClick">点击</button>
</view>
自定义组件的创建与使用
-
创建组件
在components目录下新建.vue文件,例如MyComponent.vue:
<template> <view> <text>{{ message }}</text> </view> </template> <script> export default { props: { message: String } } </script> -
注册组件
在页面中通过import引入并注册:<template> <view> <my-component message="自定义组件"></my-component> </view> </template> <script> import MyComponent from '@/components/MyComponent.vue' export default { components: { MyComponent } } </script>
组件的生命周期
uniapp 组件遵循 Vue 的生命周期,常用钩子包括:
created:组件实例刚创建,未挂载 DOM。mounted:DOM 挂载完成,可操作节点。updated:数据更新导致 DOM 重新渲染。
组件间的通信
-
父传子:通过
props传递数据。
<child-component :title="parentTitle"></child-component> -
子传父:通过
$emit触发父组件事件。// 子组件 this.$emit('update', newValue) // 父组件 <child-component @update="handleUpdate"></child-component> -
全局状态管理:使用
Vuex或uni.$on/uni.$emit跨组件通信。
条件编译与平台适配
通过注释实现不同平台的代码适配:
<!-- #ifdef H5 -->
<view>仅H5平台显示</view>
<!-- #endif -->
注意事项
- 组件样式默认隔离,可通过
options配置styleIsolation修改。 - 避免频繁更新组件数据,优化性能可使用
v-once或虚拟列表。 - 跨平台组件需测试各端兼容性,必要时使用条件编译。






