实现vue组件
创建 Vue 组件
Vue 组件是 Vue.js 应用的核心构建块,可以封装可复用的功能。以下是创建 Vue 组件的几种常见方式。
单文件组件 (SFC)
单文件组件是最常用的方式,将模板、逻辑和样式封装在一个 .vue 文件中。
<template>
<div>
<h1>{{ title }}</h1>
<button @click="increment">Click me</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: 'My Component',
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
全局注册组件 在 Vue 应用中全局注册组件,使其在任何地方可用。
import MyComponent from './MyComponent.vue'
app.component('MyComponent', MyComponent)
局部注册组件 仅在特定组件中注册,避免全局污染。

import MyComponent from './MyComponent.vue'
export default {
components: {
MyComponent
}
}
组件通信
Props 传递数据 父组件通过 props 向子组件传递数据。
<!-- ParentComponent.vue -->
<template>
<ChildComponent :message="parentMessage" />
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: { ChildComponent },
data() {
return {
parentMessage: 'Hello from parent'
}
}
}
</script>
<!-- ChildComponent.vue -->
<template>
<p>{{ message }}</p>
</template>
<script>
export default {
props: ['message']
}
</script>
自定义事件
子组件通过 $emit 向父组件发送事件。

<!-- ChildComponent.vue -->
<template>
<button @click="notifyParent">Notify Parent</button>
</template>
<script>
export default {
methods: {
notifyParent() {
this.$emit('notify', 'Child clicked')
}
}
}
</script>
<!-- ParentComponent.vue -->
<template>
<ChildComponent @notify="handleNotification" />
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: { ChildComponent },
methods: {
handleNotification(message) {
console.log(message)
}
}
}
</script>
生命周期钩子
Vue 组件提供多个生命周期钩子,用于在不同阶段执行逻辑。
export default {
created() {
console.log('Component created')
},
mounted() {
console.log('Component mounted to DOM')
},
updated() {
console.log('Component updated')
},
destroyed() {
console.log('Component destroyed')
}
}
动态组件
使用 <component> 标签和 is 属性动态切换组件。
<template>
<component :is="currentComponent" />
<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>
插槽 (Slots)
插槽允许父组件向子组件注入内容。
<!-- ChildComponent.vue -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<!-- ParentComponent.vue -->
<template>
<ChildComponent>
<template v-slot:header>
<h1>Header Content</h1>
</template>
<p>Default slot content</p>
<template v-slot:footer>
<p>Footer Content</p>
</template>
</ChildComponent>
</template>






