vue组件实现
Vue 组件实现的基本概念
Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。每个组件封装了自己的模板、逻辑和样式,便于维护和协作开发。
组件的定义与注册
在 Vue 中,组件可以通过单文件组件(.vue 文件)或全局/局部注册的方式定义。单文件组件是最常见的方式,结构清晰,适合大型项目。
<template>
<div class="example-component">
{{ message }}
</div>
</template>
<script>
export default {
name: 'ExampleComponent',
data() {
return {
message: 'Hello, Vue!'
}
}
}
</script>
<style scoped>
.example-component {
color: blue;
}
</style>
全局注册通过 Vue.component 实现:
Vue.component('example-component', {
template: '<div>{{ message }}</div>',
data() {
return { message: 'Global Component' }
}
})
局部注册在父组件中通过 components 选项引入:
import ExampleComponent from './ExampleComponent.vue'
export default {
components: {
ExampleComponent
}
}
组件通信
Vue 组件通信方式包括 props、自定义事件、插槽和 Vuex/Pinia 状态管理。
Props 向下传递数据
父组件通过 props 向子组件传递数据:
<template>
<child-component :title="parentTitle" />
</template>
<script>
export default {
data() {
return { parentTitle: 'From Parent' }
}
}
</script>
子组件通过 props 接收:
export default {
props: ['title']
}
自定义事件向上通信
子组件通过 $emit 触发事件:
this.$emit('update', newValue)
父组件监听事件:
<child-component @update="handleUpdate" />
插槽(Slots)
插槽用于内容分发,支持默认插槽和具名插槽。
<!-- 父组件 -->
<template>
<child-component>
<template v-slot:header>
<h1>Header Content</h1>
</template>
<p>Default Slot Content</p>
</child-component>
</template>
<!-- 子组件 -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
</div>
</template>
生命周期钩子
Vue 组件提供生命周期钩子,便于在不同阶段执行逻辑:
created:实例创建后,DOM 未挂载。mounted:DOM 挂载完成。updated:数据更新导致 DOM 重新渲染后。destroyed:实例销毁后。
export default {
created() {
console.log('Component created')
},
mounted() {
console.log('DOM mounted')
}
}
动态组件与异步组件
动态组件通过 <component :is="currentComponent"> 切换显示。异步组件通过动态导入实现代码分割:
const AsyncComponent = () => import('./AsyncComponent.vue')
组合式 API(Vue 3)
Vue 3 的组合式 API 提供更灵活的代码组织方式:

<script setup>
import { ref, onMounted } from 'vue'
const count = ref(0)
onMounted(() => {
console.log('Component mounted')
})
</script>
<template>
<button @click="count++">{{ count }}</button>
</template>
最佳实践
- 使用单文件组件(SFC)保持模块化。
- Props 定义类型和默认值:
props: { title: { type: String, default: 'Default Title' } } - 避免直接修改 props,通过事件通知父组件。
- 为组件命名(
name选项)便于调试。 - 样式使用
scoped属性避免污染全局样式。






