Vue 组件库 Button实现

242 阅读1分钟

Vue 组件库 Button实现

下面是一个类似于Ant Design Vue的Button组件的实现,支持传入图标、loading等状态。

<template>
  <button class="btn" :class="classes" :disabled="disabled" @click="onClick">
    <i v-if="icon" :class="['iconfont', `icon-${icon}`]"></i>
    <span v-if="!loading"><slot></slot></span>
    <span v-else><i class="iconfont icon-loading"></i></span>
  </button>
</template>

<script>
export default {
  name: 'Button',
  props: {
    type: {
      type: String,
      default: 'default'
    },
    size: {
      type: String,
      default: 'medium'
    },
    icon: {
      type: String,
      default: ''
    },
    loading: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    classes() {
      return [
        `btn-${this.type}`,
        `btn-${this.size}`
      ]
    }
  },
  methods: {
    onClick() {
      if (!this.loading && !this.disabled) {
        this.$emit('click')
      }
    }
  }
}
</script>

<style scoped>
.btn {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  outline: none;
  border: none;
  padding: 8px 16px;
  font-size: 14px;
}

.btn-default {
  background-color: #fff;
  color: #333;
  border: 1px solid #ccc;
}

.btn-primary {
  background-color: #1890ff;
  color: #fff;
}

.btn-success {
  background-color: #52c41a;
  color: #fff;
}

.btn-warning {
  background-color: #faad14;
  color: #fff;
}

.btn-danger {
  background-color: #f5222d;
  color: #fff;
}

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

.btn-medium {
  font-size: 14px;
  padding: 8px 16px;
}

.btn-large {
  font-size: 16px;
  padding: 12px 24px;
}

.iconfont {
  font-family: 'iconfont';
  font-size: 16px;
  margin-right: 4px;
}
</style>

这个组件的实现与Ant Design Vue的Button组件很相似。它支持传入类型、尺寸、图标、loading状态和禁用状态。它还使用插槽来允许在按钮内部插入任何内容。

希望这个例子能帮助你更好地理解如何实现Vue组件库。