在 Vue 中,封装组件可以使代码更加模块化和灵活,提高代码的复用性和可维护性。下面是一个简单的封装组件的示例:
1.创建组件
<template>
<div class="my-button" :class="{ 'is-disabled': disabled }" @click="handleClick">
{
{
text }}
</div>
</template>
<script>
export default {
name: 'MyButton',
props: {
text: {
type: String,
required: true
},
disabled: {
type: Boolean,
default: false
}
},
methods: {
handleClick() {
if (!this.disabled) {
this.$emit('click');
}
}
}
};
</script>
<style>
.my-button {
display: inline-block;
padding: 8px 16px;
background-color: #42b983;
color: #fff;
cursor: pointer;
border-radius: 4px;
}
.is-disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
2.在其他组件中引用
<template>
<div>
<my-button text="Click Me" @click="handleClick" />
</div>
</template>
<script>
import MyButton from './MyButton.vue';
export default {
components: {
MyButton
},
methods: {
handleClick() {
console.log('button clicked');
}
}
};
</script>
使用 import 引入组件,并在 components 中注册,在模板中使用即可。
需要注意的是,组件名应该使用 PascalCase 风格(即首字母大写),以便 Vue 能够正确地解析组件名称。另外,可以在组件中定义 props、methods、data 等属性和方法,也可以使用 slot 来进行插槽相关的操作。