如何封装、注册和使用一个button组件

162 阅读1分钟

如何封装、注册和使用一个button组件

1. 在component文件夹下创建 Button 组件,设置基本内容,并设置name属性,name:'XjName'

<template>
  <button class="xj-button">按钮</button>
</template>

<script>
export default {
  name: 'XjButton'
}
</script>

2. 接下来还不能使用,需要到main下面进行全局注册

2.1 导入组件

import XjButton from './components/Button'

2.2 注册组件,设置(组件名,组件)

Vue.component(XjButton.name, XjButton)

3. 注册完成后,就能在App.vue中使用了

<template>
  <div id="app">
    <xj-button></xj-button>
  </div>
</template>

以上,一个简单的button组件就封装完成了

4.添加slot插槽

前面已经封装好了一个button组件,但是app引入组件内容是写死的,如何让它的文字由app控制呢?添加slot插槽,可以在slot外包裹span,控制样式

Button.vue

<template>
  <button class="xj-button">
    <span>
      <slot></slot>
    </span>
  </button>
</template>

<script>
export default {
  name: 'XjButton'
}
</script>

App.vue

<template>
  <div id="app">
    <xj-button>登录</xj-button>
  </div>
</template>

5.添加type属性

子组件通过props接收属性,并传入限制传入类型和默认值设置

App.vue

  <div id="app">
    <xj-button>按钮</xj-button>
    <xj-button type='primary'>primary按钮</xj-button>
    <xj-button type='success'>success按钮</xj-button>
    <xj-button type='info'>info按钮</xj-button>
    <xj-button type='danger'>danger按钮</xj-button>
    <xj-button type='warning'>warning按钮</xj-button>
  </div>

Button.vue

<template>
  <button class="xj-button">
    <span>
      <slot></slot>
    </span>
  </button>
</template>

<script>
export default {
  name: 'XjButton',
  props: {
    type: {
      type: String,
      default: 'default'
    }
  }
}
5.1 为每个type添加各自的样式

Button.vue

<template>
  <button class="xj-button"
          :class="`xj-button-${type}`">
    <span>
      <slot></slot>
    </span>
  </button>
</template>

<script>
export default {
  name: 'XjButton',
  props: {
    type: {
      type: String,
      default: 'default'
    }
  }
}
</script>

如果还需要添加更多属性,只需要按照上面的步骤,例如:添加circle属性、添加round属性、添加disabled属性等等。

6.注册点击事件

点击事件内容是由用户自己定义,我们封装组件只需要返回一个事件即可

App.vue

<xj-button @click="fn">按钮</xj-button>

  methods: {
    fn () {
      console.log('666')
    }
  }

Button.vue

  <button @click="handleClick">
    <span>
      <slot></slot>
    </span>
  </button>
  
    methods: {
    handleClick (e) {
      this.$emit('click', e)
    }
  }

后面再根据自己的样式风格进行优化即可,至此就封装好了一个button组件