Vue组件实现方法
Vue 组件的基本实现
Vue 组件是 Vue.js 的核心概念之一,用于封装可复用的代码。组件可以包含模板、逻辑和样式。
定义单文件组件 (SFC)
<template>
<div>
<h1>{{ title }}</h1>
<button @click="handleClick">Click Me</button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
props: {
title: {
type: String,
default: 'Default Title'
}
},
methods: {
handleClick() {
this.$emit('button-clicked');
}
}
}
</script>
<style scoped>
h1 {
color: blue;
}
</style>
全局注册组件
全局注册的组件可以在任何地方使用,无需单独导入。
import Vue from 'vue';
import MyComponent from './MyComponent.vue';
Vue.component('my-component', MyComponent);
局部注册组件
局部注册的组件仅在当前组件中可用。

import MyComponent from './MyComponent.vue';
export default {
components: {
'my-component': MyComponent
}
}
使用 Props 传递数据
Props 用于从父组件向子组件传递数据。
<template>
<child-component :message="parentMessage"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent'
}
}
}
</script>
使用事件通信
子组件可以通过 $emit 触发事件,父组件监听这些事件。
<template>
<button @click="notifyParent">Notify Parent</button>
</template>
<script>
export default {
methods: {
notifyParent() {
this.$emit('notify', 'Data from child');
}
}
}
</script>
插槽 (Slots) 的使用
插槽允许父组件向子组件插入内容。

<!-- Child Component -->
<template>
<div>
<slot></slot>
</div>
</template>
<!-- Parent Component -->
<template>
<child-component>
<p>This content is slotted into the child component</p>
</child-component>
</template>
动态组件
使用 <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>
生命周期钩子
Vue 组件提供多个生命周期钩子,用于在不同阶段执行代码。
export default {
created() {
console.log('Component created');
},
mounted() {
console.log('Component mounted to DOM');
},
beforeDestroy() {
console.log('Component will be destroyed');
}
}
使用 Mixins
Mixins 是一种分发组件可复用功能的方式。
const myMixin = {
created() {
this.hello();
},
methods: {
hello() {
console.log('Hello from mixin!');
}
}
}
export default {
mixins: [myMixin]
}






