vue 组件实现
Vue 组件实现
Vue 组件是 Vue.js 的核心概念之一,允许开发者将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的常见方法:
单文件组件 (SFC)
单文件组件是 Vue 中最常用的组件形式,以 .vue 为扩展名,包含模板、脚本和样式三部分。
<template>
<div class="example">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
.example {
color: red;
}
</style>
全局注册组件
通过 Vue.component 方法全局注册组件,可以在任何地方使用。
Vue.component('my-component', {
template: '<div>A custom component!</div>'
});
局部注册组件
在组件选项中通过 components 属性局部注册组件,仅在当前组件内可用。
const ChildComponent = {
template: '<div>A child component!</div>'
};
new Vue({
components: {
'child-component': ChildComponent
}
});
动态组件
使用 <component> 标签和 is 属性实现动态组件切换。

<template>
<component :is="currentComponent"></component>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentComponent: 'ComponentA'
}
},
components: {
ComponentA,
ComponentB
}
}
</script>
函数式组件
适用于无状态、无实例的组件,通过 functional: true 声明。
Vue.component('functional-button', {
functional: true,
render(createElement, context) {
return createElement('button', context.data, context.children);
}
});
插槽 (Slots)
通过插槽实现内容分发,增强组件的灵活性。
<template>
<div class="container">
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
Props 数据传递
父组件通过 props 向子组件传递数据。

<template>
<child-component :message="parentMessage"></child-component>
</template>
<script>
export default {
data() {
return {
parentMessage: 'Hello from parent'
}
}
}
</script>
自定义事件
子组件通过 $emit 触发事件,父组件监听事件。
<!-- 子组件 -->
<template>
<button @click="$emit('custom-event', payload)">Click me</button>
</template>
<!-- 父组件 -->
<template>
<child-component @custom-event="handleEvent"></child-component>
</template>
生命周期钩子
组件在不同阶段会触发生命周期钩子,可用于执行特定逻辑。
export default {
created() {
console.log('Component created');
},
mounted() {
console.log('Component mounted');
}
}
混入 (Mixins)
通过混入复用组件逻辑。
const myMixin = {
created() {
this.hello();
},
methods: {
hello() {
console.log('Hello from mixin!');
}
}
};
export default {
mixins: [myMixin]
}
组合式 API (Vue 3)
Vue 3 的组合式 API 提供更灵活的代码组织方式。
<script setup>
import { ref } from 'vue';
const count = ref(0);
function increment() {
count.value++;
}
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>






