下面,我们来系统的梳理关于 Vue 组件定义 的基本知识点
一、组件化核心思想
组件(Component) 是 Vue 的核心功能,允许将 UI 拆分为独立可复用的代码单元。每个组件包含:
- 模板:声明式渲染结构
- 逻辑:处理数据与行为
- 样式:作用域 CSS(通过
<style scoped>
)
二、组件定义方式
1. 全局组件(Vue2/Vue3 通用)
// Vue2
Vue.component('my-component', {
template: '<div>全局组件</div>'
})
// Vue3
const app = createApp({
})
app.component('global-component', {
template: `<h3>Vue3全局组件</h3>`
})
特点:
- 可在任意组件模板中使用
- 适合高频复用基础组件(如 Button、Icon)
- 命名建议:全小写+连字符(如
base-button
)
2. 局部组件
// 选项式 API(Vue2/Vue3通用)
const ChildComponent = {
template: `<div>子组件 {
{ message }}</div>`,