以下是一个示例,演示了如何封装一个可复用的按钮组件:
<template>
<button :class="computedClasses" @click="handleClick">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'MyButton',
props: {
type: {
type: String,
default: 'primary',
validator: (value) => ['primary', 'secondary'].includes(value)
},
disabled: {
type: Boolean,
default: false
}
},
computed: {
computedClasses() {
return {
'my-button': true,
'my-button-primary': this.type === 'primary',
'my-button-secondary': this.type === 'secondary',
'my-button-disabled': this.disabled
}
}
},
methods: {
handleClick() {
if (!this.disabled) {
this.$emit('click');
}
}
}
}
</script>
<style scoped>
.my-button {
/* 按钮的样式 */
}
.my-button-primary {
/* 主要按钮的样式 */
}
.my-button-secondary {
/* 次要按钮的样式 */
}
.my-button-disabled {
/* 禁用按钮的样式 */
}
</style>
在这个案例中,我们创建了一个名为 MyButton
的组件。它有两个props:type
和 disabled
。type
可以是 ‘primary’ 或 ‘secondary’,默认值为 ‘primary’。disabled
是一个布尔值,默认为false。
该组件使用了一个计算属性 computedClasses
,用于根据props的值动态计算按钮的类名。在按钮的点击事件处理函数中,如果按钮没有被禁用,它会触发一个自定义的 click
事件。
你可以根据自己的需求对这个案例进行修改和扩展,封装更多的可复用组件。希望这个示例能对你有所帮助!如果你还有其他问题,请随时提问。