step1 - 初始化一个按钮
<template>
<div class="bigButton"> </div>
</template>
<style lang="scss" scoped>
.bigButton {
user-select: none; //
cursor: not-allowed; //可选,这里默认未被激活时不能被选中
border-radius: 54px;
background-color: #789be3;
width: 100%;
height: 55px;
line-height: 55px;
color: #fff;
text-align: center;
font-size: 20px;
font-weight: 400;
}
</style>
step2 - 加入hover时、active时样式变化
子组件
<template>
<div class="bigButton" :class="isActive ? 'active' : ''"></div>
// 1、 :class
</template>
<script setup> //2、
const props = defineProps({ //接收父组件传参
isActive: { //是否处于激活active状态
type: Boolean,
default: false,
},
});
</script>
<style lang="scss" scoped>
.bigButton {
user-select: none;
cursor: not-allowed;
border-radius: 54px;
background-color: #789be3;
width: 100%;
height: 55px;
line-height: 55px;
color: #fff;
text-align: center;
font-size: 20px;
font-weight: 400;
&.active { // 3、写好激活状态
background: #1352d6;
box-shadow: 0px 0px 7.6px 3px #b2bed6;
cursor: pointer;
&:hover {
background-color: #5380e1;
}
}
}
</style>
父组件
<template>
<div class="bottom">
<myButton :isActive="true"></myButton>
// 1、父传参给子
// 2、:isActive='判断逻辑表达式' 如:active="username != ''"
</div>
</template>
<script setup>
import myButton from "../components/myButton.vue";
</script>
<style lang="scss">
.bottom {
margin-top: 80px;
}
</style>
step3 - 自定义按钮文字内容
使用插槽
子组件
<template>
<div class="bigButton" :class="isActive ? 'active' : ''">
<slot></slot> //插槽
</div>
</template>
父组件
<template>
<div class="bottom">
<myButton :isActive="true">开始</myButton> // 写入内容
</div>
</template>
step4 - 添加点击事件
子组件
<template>
<div class="bigButton" :class="isActive ? 'active' : ''" @click="onclick"> //1、添加事件监听
<slot></slot>
</div>
</template>
<script setup> // 完整代码
const emits = defineEmits(["click"]); // 2、接收父组件传来的点击事件
const props = defineProps({
isActive: {
type: Boolean,
default: false,
},
});
function onclick() {
if (!props.isActive) { // 3、默认如果这时候按钮未被激活,不会有反应
return;
}
emits("click"); // 4、 调用父组件点击事件
}
</script>
父组件
<template>
<div class="bottom" @click="函数名">
<myButton :isActive="true">开始</myButton> // 写入内容
</div>
</template>
step5
成功!快封装试试吧!