【Vue3】封装按钮组件

商品详情-按钮组件

在这里插入图片描述

目的:封装一个通用按钮组件,有大、中、小、超小四种尺寸,有默认、主要、次要、灰色四种类型。

封装组件:src/components/button/index.vue

<script lang="ts" setup name="Button">
import {
    
     PropType } from 'vue'

defineProps({
    
    
  size: {
    
    
    type: String as PropType<'large' | 'middle' | 'small' | 'mini'>,
    default: 'middle',
  },
  type: {
    
    
    type: String as PropType<'default' | 'primary' | 'plain' | 'gray'>,
    default: 'default',
  },
})
</script>
<template>
  <button class="button ellipsis" :class="[size, type]">
    <slot />
  </button>
</template>

<style scoped lang="less">
.button {
    
    
  appearance: none;
  border: none;
  outline: none;
  background: #fff;
  text-align: center;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
}
.large {
    
    
  width: 240px;
  height: 50px;
  font-size: 16px;
}
.middle {
    
    
  width: 180px;
  height: 50px;
  font-size: 16px;
}
.small {
    
    
  width: 100px;
  height: 32px;
}
.mini {
    
    
  width: 60px;
  height: 32px;
}
.default {
    
    
  border-color: #e4e4e4;
  color: #666;
}
.primary {
    
    
  border-color: #27ba9b;
  background: #27ba9b;
  color: #fff;
}
.plain {
    
    
  border-color: #27ba9b;
  color: #27ba9b;
  background: lighten(#27ba9b, 50%);
}
.gray {
    
    
  border-color: #ccc;
  background: #ccc;
  color: #fff;
}
</style>

全局注册组件

import Button from '@/components/button/index.vue'
export default {
    
    
  install(app: App) {
    
    
    app.component('Button', Button)
}

定义组件类型

import Button from '@/components/button/index.vue'
declare module 'vue' {
    
    
  export interface GlobalComponents {
    
    
    Button: typeof Button
  }
}

export {
    
    }

使用组件:src/views/goods/index.vue

  <div class="spec">
    <!-- 数字选择框 -->
    <Numbox :max="info.inventory" v-model="count"></Numbox>
    <Button type="primary" style="margin-top: 20px">
      加入购物车
    </Button>
  </div>

猜你喜欢

转载自blog.csdn.net/weixin_46862327/article/details/129350020