【使用vue封装属于自己风格的组件---Button篇】

封装button组件流程

对于button组件的封装,可能较为简单,只需全局注册组件,然后校验传入该组件的props参数,最后渲染组件即可。

注册组件

我们打开入口文件–main.js,组件名字遵循骆驼写法,可自定义。

  1. 引入组件 import corningButton from ‘@/views/componets/corning-button’
  2. 注册组件 Vue.component(“corning-button”,corningButton)

编写组件代码

1.template标签代码

  <template>
    <div>
        <button :class="btnClass" @click="handlerClick" :disabled="disabled">
             <slot></slot>
        </button>
    </div>
</template>
  1. script代码
<script>
export default {
    name:"corning-button",
    props:{
        type:{
            type:String,
            default:'default',
            //添加自定义验证规则
            validator:(value)=>['default','error','warn','info'].includes(value)
        },
        disabled:{
            type:Boolean,
            default:false
        }
    },
    computed:{
        btnClass(){
            if(this.disabled){
                return `${this.type} disabled`
            }
            return this.type
        }
    },
    methods:{
        handlerClick(){
            //触发调用该组件传入的单击事件
            this.$emit("click")
        }
    }
}
</script>
  1. style代码
<style scoped>
button{
    color: #fff;
    border: none;
    border-radius: 7px;
    padding:5px 15px;
}
button:hover{
    cursor: pointer;
    opacity: 0.8;
}
.disabled:hover{
    cursor: not-allowed;
    opacity: 0.6;
}
.default{
    background: #3096e1;
}
.error{
    background: #ff826f;
}
.warn{
    background: #ffc05f;
}
.info{
    background: #54d2dc;
}
.disabled{
    opacity: .6;
}
</style>

引用调用组件

<template>
    <div>
        <corning-button type="info" @click="handlerClick" disabled>测试</corning-button>
    </div>
</template>
<script>
import corningButton from '@/components/corning-button.vue'
export default {
  components: { corningButton },
    name:"test",
    methods:{
        handlerClick(){
            console.log("触发单击事件")
        }
    }
}
</script>

效果展示

button组件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值