vue基础组件实现
Vue 基础组件实现方法
组件定义
使用 Vue 的 Vue.component() 方法或单文件组件(SFC)定义基础组件。单文件组件更常见,结构包含 <template>、<script> 和 <style> 三部分。
<template>
<button class="btn" @click="handleClick">
{{ buttonText }}
</button>
</template>
<script>
export default {
name: 'BaseButton',
props: {
buttonText: {
type: String,
default: 'Click Me'
}
},
methods: {
handleClick() {
this.$emit('click-event');
}
}
};
</script>
<style scoped>
.btn {
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
}
</style>
组件注册
全局注册通过 Vue.component(),局部注册在父组件的 components 选项中。
// 全局注册
import BaseButton from './components/BaseButton.vue';
Vue.component('BaseButton', BaseButton);
// 局部注册
export default {
components: {
BaseButton
}
};
Props 传递数据
通过 props 接收父组件传递的数据,支持类型检查和默认值。

props: {
size: {
type: String,
validator: value => ['small', 'medium', 'large'].includes(value),
default: 'medium'
}
}
事件通信
使用 $emit 触发自定义事件,父组件通过 v-on 监听。
<!-- 子组件 -->
this.$emit('submit', payload);
<!-- 父组件 -->
<BaseComponent @submit="handleSubmit" />
插槽分发内容
通过 <slot> 实现内容分发,支持默认插槽和命名插槽。

<!-- 子组件 -->
<div class="card">
<slot name="header"></slot>
<slot>Default content</slot>
</div>
<!-- 父组件 -->
<BaseCard>
<template v-slot:header>
<h2>Title</h2>
</template>
<p>Main content</p>
</BaseCard>
动态组件
使用 <component :is=""> 实现动态组件切换。
<component :is="currentComponent"></component>
组件复用
通过 Mixins 或 Composition API 复用逻辑。
// Mixin
const logMixin = {
created() {
console.log('Component created');
}
};
// Composition API
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
return { count };
}
};
最佳实践
- 组件命名采用 PascalCase
- 为重要 props 添加验证
- 使用插槽增强组件灵活性
- 复杂组件考虑使用 Composition API 组织代码
- 为可复用组件编写清晰的文档和示例
以上方法涵盖了 Vue 基础组件的核心实现技术,可根据具体需求选择适合的方式构建组件。






