vue 组件实现
Vue 组件实现方法
Vue 组件是 Vue.js 的核心概念之一,用于封装可复用的代码。以下是 Vue 组件的几种实现方式。
单文件组件 (SFC)
单文件组件将模板、逻辑和样式封装在一个 .vue 文件中,结构清晰且易于维护。
<template>
<div>
<h1>{{ title }}</h1>
<button @click="handleClick">Click Me</button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
data() {
return {
title: 'Hello Vue'
}
},
methods: {
handleClick() {
alert('Button clicked!')
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
全局组件注册
通过 Vue.component 方法注册全局组件,可以在任何地方使用。
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
new Vue({
el: '#app'
})
局部组件注册
在 Vue 实例的 components 选项中注册局部组件,仅在该实例作用域内可用。
const ChildComponent = {
template: '<div>Child Component</div>'
}
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
}
})
动态组件
使用 <component> 标签和 is 属性实现动态组件切换。
<template>
<div>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<component :is="currentComponent"></component>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
函数式组件
函数式组件无状态、无实例,适用于纯渲染场景。
Vue.component('functional-button', {
functional: true,
render(createElement, context) {
return createElement('button', context.data, context.children)
}
})
组件通信
父子组件通过 props 和 $emit 实现通信。
<!-- Parent Component -->
<template>
<child-component :message="parentMessage" @update="handleUpdate" />
</template>
<script>
export default {
data() {
return {
parentMessage: 'Hello from parent'
}
},
methods: {
handleUpdate(newMessage) {
this.parentMessage = newMessage
}
}
}
</script>
<!-- Child Component -->
<template>
<div>
<p>{{ message }}</p>
<button @click="notifyParent">Notify Parent</button>
</div>
</template>
<script>
export default {
props: ['message'],
methods: {
notifyParent() {
this.$emit('update', 'New message from child')
}
}
}
</script>
插槽 (Slots)
插槽用于内容分发,实现更灵活的组件结构。
<!-- Parent Component -->
<template>
<child-component>
<template v-slot:header>
<h1>Header Content</h1>
</template>
<p>Default slot content</p>
</child-component>
</template>
<!-- Child Component -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
</div>
</template>
混入 (Mixins)
混入用于复用组件选项逻辑。

const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('Hello from mixin!')
}
}
}
export default {
mixins: [myMixin]
}






