当前位置:首页 > uni-app

uniapp组件

2026-01-13 18:58:47uni-app

uniapp组件基础概念

uniapp的组件系统基于Vue.js,支持跨平台开发(H5、小程序、App等)。组件分为内置基础组件(如<view><button>)和自定义组件,需遵循特定规范实现跨平台兼容。

内置组件

uniapp提供以下常用内置组件:

  • 视图容器<view><scroll-view><swiper>
  • 表单元素<input><checkbox><picker>
  • 导航<navigator>(类似<a>标签)
  • 媒体<image><video>
  • 地图<map>(需平台支持)

示例:

<template>
  <view class="container">
    <button @click="handleClick">点击</button>
  </view>
</template>

自定义组件开发

  1. 创建组件文件
    components目录下新建.vue文件,例如my-component.vue

    <template>
      <view>{{ message }}</view>
    </template>
    <script>
    export default {
      props: ['message'],
      data() {
        return { localData: '局部数据' }
      }
    }
    </script>
  2. 注册组件
    全局注册:在main.js中通过Vue.component注册。
    局部注册:在页面中通过components选项引入:

    uniapp组件

    import MyComponent from '@/components/my-component.vue';
    export default {
      components: { MyComponent }
    }
  3. 使用组件
    在模板中直接使用:

    <my-component message="传递数据"></my-component>

组件通信

  • 父传子:通过props传递数据。

  • 子传父:通过$emit触发事件:

    uniapp组件

    // 子组件
    this.$emit('custom-event', payload);
    
    // 父组件
    <child-component @custom-event="handleEvent"></child-component>
  • 跨级通信:使用provide/inject或全局状态管理(如Vuex)。

生命周期

uniapp组件生命周期与Vue一致,常用钩子:

  • created:组件实例创建后调用。
  • mounted:DOM挂载完成。
  • updated:数据更新导致DOM重新渲染后触发。

平台差异处理

通过条件编译解决跨平台兼容问题:

<!-- #ifdef MP-WEIXIN -->
<view>仅微信小程序显示</view>
<!-- #endif -->

注意事项

  1. 组件样式默认隔离,可通过options配置styleIsolation调整。
  2. 小程序端自定义组件需在pages.json中配置usingComponents
  3. 避免频繁更新大数据量的props,可能影响性能。

通过合理使用组件化开发,能有效提升uniapp项目的可维护性和复用性。

标签: 组件uniapp
分享给朋友:

相关文章

vue实现下拉刷新组件

vue实现下拉刷新组件

实现下拉刷新组件的核心思路 下拉刷新功能通常通过监听触摸事件、滚动位置和动画效果实现。Vue中可以利用自定义指令或封装组件完成,以下为两种常见实现方式。 基于自定义指令的实现 创建指令监听触摸事件,…

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

Vue 拖拽实现组件嵌套 使用 Vue 实现拖拽组件嵌套功能可以通过原生 HTML5 拖拽 API 或第三方库如 vuedraggable 实现。以下是两种方法的详细说明: 使用 HTML5 拖拽…

vue轮播组件实现

vue轮播组件实现

Vue 轮播组件实现方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template&g…

vue实现组件封装

vue实现组件封装

Vue 组件封装方法 封装组件的基本步骤 创建独立的 .vue 文件,包含 template、script 和 style 三个部分。通过 props 接收父组件传递的数据,使用 $emit 触发自…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性,或者使用第三方 UI 库…

vue动态组件实现

vue动态组件实现

Vue 动态组件实现方法 使用 component 标签与 is 属性 通过 Vue 内置的 <component> 标签和 is 属性实现动态组件切换。is 的值可以是已注册的组件名或导…