vue3组件封装模板,例如封装button
时间: 2023-10-20 15:21:56 浏览: 68
下面是一个简单的 Vue 3 组件封装模板,以封装一个 Button 组件为例:
```vue
<template>
<button :class="computedClass" @click="handleClick">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'MyButton',
props: {
type: {
type: String,
default: 'default'
},
disabled: {
type: Boolean,
default: false
}
},
computed: {
computedClass() {
return `my-button my-button-${this.type} ${this.disabled ? 'my-button-disabled' : ''}`
}
},
methods: {
handleClick() {
if (!this.disabled) {
this.$emit('click')
}
}
}
}
</script>
<style scoped>
.my-button {
border: 1px solid #ccc;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
}
.my-button-default {
background-color: #fff;
color: #333;
}
.my-button-primary {
background-color: #007bff;
color: #fff;
}
.my-button-disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
```
这个组件具有以下特点:
- 可以接收`type`和`disabled`两个属性,分别表示按钮类型和是否禁用
- 通过计算属性`computedClass`来根据属性值动态生成 CSS 类名,从而实现样式的动态切换
- 当按钮被点击时,先判断是否禁用,如果没有禁用则触发`click`事件
使用方式:
```vue
<template>
<my-button type="primary" :disabled="isDisabled" @click="handleClick">
{{ buttonText }}
</my-button>
</template>
<script>
import MyButton from './MyButton.vue'
export default {
components: {
MyButton
},
data() {
return {
isDisabled: false,
buttonText: 'Click me'
}
},
methods: {
handleClick() {
alert('Button clicked')
}
}
}
</script>
```