vue实现组件
Vue 实现组件的方法
单文件组件 (SFC)
使用 .vue 文件格式,包含 <template>、<script> 和 <style> 三个部分:
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data() {
return {
msg: 'Hello Vue!'
}
}
}
</script>
<style scoped>
.example {
color: red;
}
</style>
全局注册
通过 Vue.component() 方法全局注册组件:
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
局部注册
在组件选项中通过 components 属性局部注册:
const ComponentA = { /* ... */ }
const ComponentB = { /* ... */ }
new Vue({
el: '#app',
components: {
'component-a': ComponentA,
'component-b': ComponentB
}
})
动态组件
使用 <component> 元素配合 is 特性实现动态组件:
<template>
<component :is="currentComponent"></component>
</template>
<script>
export default {
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
函数式组件
无状态、无实例的轻量组件:
Vue.component('functional-button', {
functional: true,
render(createElement, context) {
return createElement('button', context.data, context.children)
}
})
组件通信
-
Props 向下传递:
<child-component :message="parentMsg"></child-component> -
Events 向上传递:
<button @click="$emit('enlarge-text')">Enlarge text</button> -
Provide/Inject:
// 父组件 provide() { return { theme: this.theme } } // 子组件 inject: ['theme']
插槽
内容分发机制:
<!-- 父组件 -->
<alert-box>
Something bad happened.
</alert-box>
<!-- 子组件 -->
<template>
<div class="alert-box">
<slot></slot>
</div>
</template>
组合式 API
Vue 3 的 setup() 函数:

<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return { count }
}
}
</script>






