uniapp 开发小组件的详细教程

最近在学习uniapp开发,想尝试制作一些小组件,但不太清楚具体步骤和注意事项。请问有没有详细的小组件开发教程?主要想了解:1)如何创建和注册组件;2)组件间通信的最佳实践;3)如何优化组件性能;4)有没有推荐的常用组件模板可以参考?希望能包含代码示例和常见问题解决方案,谢谢!

2 回复

UniApp开发小组件步骤:

  1. 创建组件:新建.vue文件,写template、script、style
  2. 注册组件:在pages.json或页面内usingComponents引入
  3. 使用组件:在页面template中写标签
  4. 传参:props接收父组件数据
  5. 通信:$emit触发父组件事件

示例:按钮组件可自定义文字和点击事件。


Uniapp 开发小组件详细教程

1. 创建组件

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

<template>
  <view class="my-component">
    <text>{{ title }}</text>
    <button @click="handleClick">点击我</button>
  </view>
</template>

<script>
export default {
  name: "MyComponent",
  props: {
    title: {
      type: String,
      default: "默认标题"
    }
  },
  methods: {
    handleClick() {
      this.$emit('customEvent', '组件被点击了')
    }
  }
}
</script>

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

2. 注册组件

全局注册(推荐)

main.js 中:

import MyComponent from '@/components/my-component.vue'

Vue.component('MyComponent', MyComponent)

局部注册

在页面中:

<script>
import MyComponent from '@/components/my-component.vue'

export default {
  components: {
    MyComponent
  }
}
</script>

3. 使用组件

<template>
  <view>
    <MyComponent 
      title="我的组件" 
      @customEvent="onCustomEvent"
    />
  </view>
</template>

<script>
export default {
  methods: {
    onCustomEvent(data) {
      console.log('接收到组件事件:', data)
    }
  }
}
</script>

4. 组件通信方式

Props 传值

<!-- 父组件 -->
<MyComponent :user="userData" />

<!-- 子组件 -->
<script>
export default {
  props: {
    user: {
      type: Object,
      default: () => ({})
    }
  }
}
</script>

事件通信

// 子组件触发
this.$emit('update', newData)

// 父组件监听
<MyComponent @update="onUpdate" />

使用 Vuex 状态管理

// store.js
export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

5. 组件生命周期

<script>
export default {
  beforeCreate() {
    console.log('组件实例化之前')
  },
  mounted() {
    console.log('组件挂载完成')
  },
  beforeDestroy() {
    console.log('组件销毁前')
  }
}
</script>

6. 插槽使用

<!-- 组件定义 -->
<template>
  <view class="card">
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </view>
</template>

<!-- 组件使用 -->
<MyCard>
  <template v-slot:header>
    <text>标题</text>
  </template>
  
  <text>主要内容</text>
  
  <template v-slot:footer>
    <button>操作按钮</button>
  </template>
</MyCard>

7. 注意事项

  1. 样式隔离:使用 scoped 属性避免样式污染
  2. 平台差异:使用条件编译处理不同平台差异
  3. 性能优化:避免在组件中定义大量数据
  4. 命名规范:组件名使用 PascalCase

8. 最佳实践

  • 保持组件单一职责
  • 合理使用 props 验证
  • 及时销毁定时器和事件监听
  • 使用 computed 和 watch 处理响应式数据

通过以上步骤,你可以快速上手 Uniapp 组件开发,构建可复用的 UI 组件。

回到顶部