当前位置:首页 > 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 监听:

<MyComponent @update="handleUpdate" />

插槽使用

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

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

父组件传递内容:

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

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

<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 组件开发的核心写法和最佳实践,可根据实际需求组合使用这些特性。

uniapp组件写法

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

相关文章

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

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

vue实现下拉框组件

vue实现下拉框组件

Vue 下拉框组件实现 基础实现 创建基础下拉框组件,使用v-model实现双向数据绑定: <template> <div class="dropdown">…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性来完成。以下是几种常见的实…

vue实现秒表组件

vue实现秒表组件

实现秒表组件的基本思路 使用Vue实现秒表组件需要管理时间状态、控制计时器的启动/暂停/重置功能,并通过计算属性动态显示格式化时间。核心逻辑包括利用setInterval更新计时数据,并通过生命周期钩…

vue实现分页组件

vue实现分页组件

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

vue实现树组件

vue实现树组件

Vue 树形组件的实现方法 递归组件实现 使用 Vue 的递归组件特性可以轻松实现树形结构。定义一个组件,该组件能够调用自身来渲染子节点。 <template> <ul>…