一、内置组件快速上手
Uniapp 提供丰富的内置组件,以下为常用组件示例:
-
基础组件
<template> <view> <text>文本组件</text> <button @click="handleClick">按钮组件</button> <image src="/static/logo.png" mode="aspectFit" /> </view> </template> -
表单组件
<template> <view> <input v-model="inputValue" placeholder="输入框" /> <switch @change="switchChange" /> <picker @change="pickerChange" :range="options" /> </view> </template> -
导航组件
<navigator url="/pages/home/index" open-type="navigate"> <text>跳转到首页</text> </navigator>
二、自定义组件开发
通过以下步骤创建自定义组件:
-
创建组件文件
在components目录新建MyComponent.vue:<template> <view class="custom-box"> <text>{{ title }}</text> <slot></slot> </view> </template> <script> export default { props: { title: { type: String, default: "默认标题" } } } </script> <style scoped> .custom-box { padding: 20rpx; border: 1px solid #eee; } </style> -
全局注册组件
在main.js中添加:import MyComponent from '@/components/MyComponent.vue' Vue.component('my-component', MyComponent)
三、组件传参案例
实现父子组件数据传递:
-
父组件调用
<template> <view> <my-component :title="parentTitle" @custom-event="handleEvent"> <text>插槽内容</text> </my-component> </view> </template> <script> export default { data() { return { parentTitle: "动态标题" } }, methods: { handleEvent(data) { console.log("子组件传递的数据:", data) } } } </script> -
子组件改造
在MyComponent.vue中添加:<script> export default { methods: { sendData() { this.$emit('custom-event', { value: Math.random() }) } } } </script>
四、组件通信总结
| 通信方式 | 方向 | 示例 |
|---|---|---|
| Props 传参 | 父 → 子 | :title="parentTitle" |
| 事件发射 | 子 → 父 | this.$emit('event') |
| 插槽 Slot | 父 → 子 | <slot name="footer"> |
| Vuex 状态管理 | 跨组件 | this.$store.state.data |
最佳实践:
- 简单数据流使用 Props/Events
- 复杂场景使用 Vuex 状态管理
- 通过
ref调用子组件方法:// 父组件 <my-component ref="childComp" /> this.$refs.childComp.doSomething()
1837

被折叠的 条评论
为什么被折叠?



