Uniapp 组件使用:内置组件快速上手 + 自定义组件开发

一、内置组件快速上手

Uniapp 提供丰富的内置组件,以下为常用组件示例:

  1. 基础组件

    <template>
      <view>
        <text>文本组件</text>
        <button @click="handleClick">按钮组件</button>
        <image src="/static/logo.png" mode="aspectFit" />
      </view>
    </template>
    

  2. 表单组件

    <template>
      <view>
        <input v-model="inputValue" placeholder="输入框" />
        <switch @change="switchChange" />
        <picker @change="pickerChange" :range="options" />
      </view>
    </template>
    

  3. 导航组件

    <navigator url="/pages/home/index" open-type="navigate">
      <text>跳转到首页</text>
    </navigator>
    


二、自定义组件开发

通过以下步骤创建自定义组件:

  1. 创建组件文件
    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>
    

  2. 全局注册组件
    main.js 中添加:

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


三、组件传参案例

实现父子组件数据传递:

  1. 父组件调用

    <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>
    

  2. 子组件改造
    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

最佳实践

  1. 简单数据流使用 Props/Events
  2. 复杂场景使用 Vuex 状态管理
  3. 通过 ref 调用子组件方法:
    // 父组件
    <my-component ref="childComp" />
    this.$refs.childComp.doSomething()
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值