封装一个Button按钮组件(vue)

首先,共公共组件有很多种类型,如按钮、表单、对话框等等,因此需要根据具体情况选择封装的组件类型。这里以按钮组件为例,介绍如何封装一个共公共按钮组件。

  1. 创建组件文件

在项目的组件目录中创建一个 Button.vue 文件,并添加以下基本代码:

<template>
  <button class="btn" :class="[typeClass, sizeClass]" @click="$emit('click')">
    <slot></slot>
  </button>
</template>

<script>
export default {
  name: "Button",
  props: {
    type: {
      type: String,
      default: 'default'
    },
    size: {
      type: String,
      default: 'medium'
    }
  },
  computed: {
    typeClass() {
      return `btn-${this.type}`
    },
    sizeClass() {
      return `btn-${this.size}`
    }
  }
}
</script>

<style scoped>
.btn {
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  outline: none;
}

.btn-default {
  background-color: #f5f5f5;
}

.btn-primary {
  background-color: #007bff;
  color: #fff;
}

.btn-secondary {
  background-color: #6c757d;
  color: #fff;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-large {
  padding: 12px 24px;
  font-size: 18px;
}
</style>
  1. 2添加组件 props

在上面的代码中,我们定义了两个 props:type 和 size。这两个 props 分别用于设置按钮的样式和尺寸。在组件中,我们使用了计算属性来根据 props 计算样式类名,然后绑定到按钮元素上。此外,我们还在按钮元素上绑定了一个 click 事件,并通过 $emit 方法触发了 Button 组件的 click 事件。

  1. 3使用组件

在需要使用 Button 组件的地方,我们可以通过以下代码使用:

<template>
  <div>
    <Button>Default Button</Button>
    <Button type="primary">Primary Button</Button>
    <Button type="secondary" size="small">Small Secondary Button</Button>
  </div>
</template>

<script>
import Button from '@/components/Button.vue';

export default {
  name: "Example",
  components: {
    Button
  }
}
</script>

在组件的 <template> 中,我们简单地使用了 Button 组件,并传递了一些 props。在 <script> 部分,我们引入了 Button 组件,并在 components 属性中注册了它。现在,我们就可以在页面中看到我们封装的共公共按钮组件了。

当然,以上是基础的封装,根据实际项目需求,我们需要在封装组件时根据场景需求,添加更多的 props、方法以及事件等。

猜你喜欢

转载自blog.csdn.net/weixin_42602736/article/details/130870513