当前位置:首页 > uni-app

uniapp组件写法

2026-03-04 19:10:16uni-app

uniapp 组件的基本结构

uniapp 的组件采用 Vue 单文件组件(SFC)的写法,包含 <template><script><style> 三个部分。以下是一个基础示例:

<template>
  <view class="my-component">
    <text>{{ message }}</text>
  </view>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    message: {
      type: String,
      default: 'Hello uniapp'
    }
  },
  data() {
    return {
      localData: 'Local data'
    }
  },
  methods: {
    handleClick() {
      this.$emit('customEvent', 'Event payload')
    }
  }
}
</script>

<style scoped>
.my-component {
  padding: 20rpx;
}
</style>

组件注册方式

全局注册
main.js 中全局注册组件:

import MyComponent from '@/components/MyComponent.vue'
Vue.component('MyComponent', MyComponent)

局部注册
在页面或父组件中局部引入:

<script>
import MyComponent from '@/components/MyComponent.vue'
export default {
  components: { MyComponent }
}
</script>

组件通信方式

Props 传值
父组件通过属性传递数据:

<MyComponent :message="parentData" />

事件触发
子组件通过 $emit 触发父组件事件:

this.$emit('update', newValue)

父组件监听事件
父组件通过 @eventName 监听:

uniapp组件写法

<MyComponent @update="handleUpdate" />

插槽使用

默认插槽
子组件定义插槽:

<template>
  <view>
    <slot></slot>
  </view>
</template>

父组件传递内容:

<MyComponent>
  <text>插入的内容</text>
</MyComponent>

具名插槽
子组件定义具名插槽:

uniapp组件写法

<slot name="header"></slot>

父组件指定插槽:

<template v-slot:header>
  <text>头部内容</text>
</template>

生命周期

uniapp 组件支持 Vue 的生命周期钩子:

export default {
  created() {
    console.log('组件实例创建完成')
  },
  mounted() {
    console.log('组件挂载到DOM')
  }
}

样式作用域

使用 scoped 属性限定样式作用域:

<style scoped>
/* 仅作用于当前组件 */
</style>

平台差异处理

通过条件编译处理多平台差异:

<template>
  <!-- #ifdef H5 -->
  <div>H5专属内容</div>
  <!-- #endif -->
</template>

组件优化建议

  • 复杂组件建议拆分为多个子组件
  • 频繁更新的数据使用 computed 计算属性
  • 避免在模板中写复杂逻辑
  • 使用 v-ifv-show 合理控制渲染

以上是 uniapp 组件开发的核心写法和最佳实践,可根据实际需求组合使用这些特性。

标签: 写法组件
分享给朋友:

相关文章

elementui组件

elementui组件

ElementUI 组件概述 ElementUI 是一套基于 Vue.js 的桌面端组件库,提供丰富的 UI 组件,适用于快速开发中后台系统。以下是其核心组件分类及典型用法。 基础组件 Button…

vue实现组件跟随

vue实现组件跟随

Vue 实现组件跟随效果 实现组件跟随效果通常需要监听鼠标或触摸事件,动态更新组件位置。以下是几种常见实现方式: 使用鼠标事件绑定 <template> <div class=…

vue 实现组件刷新

vue 实现组件刷新

组件局部刷新 在Vue中实现组件刷新可以通过强制重新渲染组件来实现。常用的方法有以下几种: 使用v-if指令 通过切换v-if条件触发组件的销毁和重建 <template> <…

vue实现分页组件

vue实现分页组件

Vue 分页组件实现 基础分页组件结构 创建一个名为 Pagination.vue 的文件,包含以下基础模板和逻辑: <template> <div class="pagina…

vue实现路由组件

vue实现路由组件

Vue 实现路由组件的方法 在 Vue 中实现路由功能通常需要结合 Vue Router 库,以下是具体实现步骤: 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router…

vue实现列表组件

vue实现列表组件

Vue 列表组件实现方法 基础列表渲染 使用 v-for 指令渲染数组数据,需配合 :key 提升性能: <template> <ul> <li v-for…