preface

While it’s comfortable to use the elementUI component library, have you wondered how the El-Button is packaged? How to encapsulate your own button component


First, the meaning of encapsulation

  • Unity of button styles in projects
  • Code reuse, high maintainability

Two, how to package?

Used in many places, encapsulated as global components. Put it in the SRC/Components directory as before

1. The encapsulation

SRC /components create a new my-button.vue file

The code is as follows (example) :

<template>
  <button class="my-button ellipsis" :class="[size, type]">
    <slot />
  </button>
</template>
<script>
export default {
  name: 'MyButton',
  props: {
    size: {
      type: String,
      default: 'middle'
    },
    type: {
      type: String,
      default: 'default'
    }
  }
}
</script>
<style scoped lang="less">
.my-button {
  margin-right: 5px;
  appearance: none;
  border: none;
  outline: none;
  background: #fff;
  text-align: center;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
}
.ellipsis {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.large {
  width: 240px;
  height: 50px;
  font-size: 16px;
}
.middle {
  width: 180px;
  height: 50px;
  font-size: 16px;
}
.small {
  width: 100px;
  height: 32px;
  font-size: 14px;
}
.mini {
  width: 60px;
  height: 32px;
  font-size: 14px;
}
.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>

Copy the code

2. Use

Use in any.vue ending file

The code is as follows (example) :

The text passed in the tag is passed to the default slot of the encapsulated public component

<template>
  <div class="home-banner">
    <my-button type="default" size="mini"> default </my-button> <my-buttontype="plain" size="mini""> </my-button> <my-buttontype="primary" size="mini"</my-button> <my-buttontype="gray" size="mini"</my-button> <br /><br />< my-buttontype="default" size="mini"</my-button> <my-buttontype="plain" size="small""> </my-button> <my-buttontype="primary" size="middle"</my-button> <my-buttontype="gray" size="large"</my-button> </div> </template> <script> import MyButton from'@/components/my-button.vue'
export default {
  name: 'App',
  components: {
  	MyButton
  },
  setup() {
    return {}
  }
}
</script>

<style lang="less">
.home-banner {
  margin: 100px auto;
  width: 700px;
  height: 300px;
}
</style>

Copy the code

Third, the effect demonstration


conclusion

Do nothing by halves