vue 组件实现
Vue 组件实现基础
Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。组件可以包含模板、逻辑和样式,并通过 props 和 events 与其他组件通信。
创建组件的方式
- 单文件组件 (SFC):使用
.vue文件,包含<template>、<script>和<style>三个部分。 - 全局注册:通过
Vue.component()方法注册全局可用组件。 - 局部注册:在组件选项中通过
components属性注册局部组件。
单文件组件示例
<template>
<div class="example">
<p>{{ message }}</p>
<button @click="updateMessage">Update</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
},
methods: {
updateMessage() {
this.message = 'Message updated!'
}
}
}
</script>
<style scoped>
.example {
color: blue;
}
</style>
组件通信
Props 传递数据
父组件通过 props 向子组件传递数据,子组件通过 props 选项接收。
<!-- ParentComponent.vue -->
<template>
<ChildComponent :title="parentTitle" />
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: { ChildComponent },
data() {
return {
parentTitle: 'Data from parent'
}
}
}
</script>
<!-- ChildComponent.vue -->
<template>
<h2>{{ title }}</h2>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
}
}
</script>
Events 触发动作
子组件通过 $emit 触发事件,父组件通过 v-on 监听。
<!-- ChildComponent.vue -->
<template>
<button @click="$emit('custom-event', 'payload')">Click me</button>
</template>
<!-- ParentComponent.vue -->
<template>
<ChildComponent @custom-event="handleEvent" />
</template>
<script>
export default {
methods: {
handleEvent(payload) {
console.log(payload) // 'payload'
}
}
}
</script>
插槽 (Slots)
插槽允许父组件向子组件注入内容。
<!-- ChildComponent.vue -->
<template>
<div>
<slot></slot>
</div>
</template>
<!-- ParentComponent.vue -->
<template>
<ChildComponent>
<p>Content passed from parent</p>
</ChildComponent>
</template>
生命周期钩子
Vue 组件提供多个生命周期钩子,用于在不同阶段执行代码。
export default {
created() {
// 组件实例创建后调用
},
mounted() {
// DOM 挂载后调用
},
updated() {
// 数据更新导致 DOM 重新渲染后调用
},
destroyed() {
// 组件销毁后调用
}
}
动态组件
通过 <component :is="currentComponent"> 实现动态切换组件。

<template>
<component :is="currentComponent"></component>
<button @click="toggleComponent">Toggle</button>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
data() {
return {
currentComponent: 'ComponentA'
}
},
components: { ComponentA, ComponentB },
methods: {
toggleComponent() {
this.currentComponent = this.currentComponent === 'ComponentA'
? 'ComponentB'
: 'ComponentA'
}
}
}
</script>
组件最佳实践
- 保持组件单一职责,每个组件只做一件事。
- 合理拆分大型组件为多个小型组件。
- 使用有意义的组件命名,遵循 PascalCase 命名约定。
- 为 props 定义明确的类型和默认值。
- 使用 scoped CSS 避免样式污染。






