Vue 二次封装组件的技巧及要点
warning:
这篇文章距离上次修改已过254天,其中的内容可能已经有所变动。
<template>
<div class="my-custom-button">
<!-- 使用插槽分发内容 -->
<slot></slot>
</div>
</template>
<script>
export default {
name: 'MyCustomButton',
// 可以添加更多的属性、方法和生命周期钩子
props: {
// 定义接收的属性
size: String,
disabled: Boolean
},
methods: {
// 定义方法
handleClick(event) {
if (!this.disabled) {
this.$emit('click', event);
}
}
}
}
</script>
<style scoped>
.my-custom-button {
padding: 10px;
background-color: #f0f0f0;
border: 1px solid #ddd;
text-align: center;
}
.my-custom-button:hover {
background-color: #e0e0e0;
}
.my-custom-button[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
</style>
这个例子展示了如何创建一个简单的Vue二次封装组件,其中包含了一个默认插槽,允许父组件传入任何内容。同时,它还演示了如何处理传入的属性和自定义事件,以及如何使用scoped
样式来保持组件样式的封装性。
评论已关闭