当前位置:首页 > uni-app

uniapp定义的组件

2026-03-05 11:14:57uni-app

uniapp 自定义组件的定义方式

在 uniapp 中,自定义组件是一种可复用的 UI 单元,通常用于封装特定的功能或样式。自定义组件通过 .vue 文件定义,包含模板、脚本和样式三部分。

组件文件结构示例:

<template>
  <view class="custom-component">
    <text>{{ title }}</text>
  </view>
</template>

<script>
export default {
  name: 'CustomComponent',
  props: {
    title: {
      type: String,
      default: '默认标题'
    }
  },
  data() {
    return {
      localData: '组件内部数据'
    }
  },
  methods: {
    handleClick() {
      this.$emit('customEvent', { detail: '事件数据' })
    }
  }
}
</script>

<style>
.custom-component {
  padding: 10px;
  background-color: #f5f5f5;
}
</style>

组件注册与使用

全局注册:main.js 中全局注册组件后,所有页面可直接使用:

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

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

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

模板中使用:

<template>
  <view>
    <custom-component title="传入的标题" @customEvent="handleEvent" />
  </view>
</template>

组件通信机制

Props 向下传递: 父组件通过属性向子组件传递数据:

<child-component :propName="parentData" />

Events 向上通知: 子组件通过 $emit 触发父组件监听的事件:

this.$emit('eventName', payload)

Ref 访问实例: 父组件通过 ref 直接调用子组件方法:

<child-component ref="childRef" />
<script>
this.$refs.childRef.childMethod()
</script>

组件生命周期

uniapp 自定义组件支持 Vue 的标准生命周期钩子:

  • beforeCreate / created
  • beforeMount / mounted
  • beforeUpdate / updated
  • beforeDestroy / destroyed

同时支持 uniapp 特有的应用生命周期:

  • onShow / onHide(页面级组件)
  • onLoad / onUnload(页面级组件)

组件样式隔离

通过 style 标签的 scoped 属性实现样式隔离:

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

注意事项:

  • 组件名建议使用 PascalCase 命名
  • 事件名建议使用 kebab-case 命名
  • 避免在组件中直接修改 props 值
  • 复杂组件建议使用 v-model 实现双向绑定

uniapp定义的组件

标签: 组件定义
分享给朋友:

相关文章

vue实现下拉框组件

vue实现下拉框组件

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

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

实现拖拽组件嵌套的核心思路 Vue中实现拖拽组件嵌套需要结合拖拽库(如vuedraggable)和组件递归渲染。核心在于动态管理嵌套数据结构,并通过事件传递实现层级更新。 安装必要依赖 推荐使用v…

uniapp 分页组件

uniapp 分页组件

uniapp 分页组件实现方法 在uniapp中实现分页功能,可以通过自定义组件或使用第三方组件库完成。以下是几种常见实现方式: 自定义分页组件 创建一个名为uni-pagination的组件,模…

vue 实现组件刷新

vue 实现组件刷新

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

vue实现组件通信

vue实现组件通信

Vue 组件通信方法 Vue 提供了多种方式实现组件间的通信,适用于不同场景。以下是常见的方法: Props 和 Events 父组件通过 props 向子组件传递数据,子组件通过 $emit…

vue表格组件实现

vue表格组件实现

Vue表格组件实现 基础表格实现 使用el-table组件实现基础表格功能。安装Element UI后,引入el-table和el-table-column组件。 <template>…