vue单页面组件实现
Vue 单页面组件实现
Vue 单页面组件(Single File Component,SFC)是 Vue.js 的核心特性之一,通过 .vue 文件将模板、逻辑和样式封装在一个文件中,实现高内聚低耦合的开发模式。
基本结构
一个典型的 .vue 文件包含以下三部分:
<template>
<!-- HTML 模板 -->
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
/* 组件作用域 CSS */
div {
color: red;
}
</style>
组件注册与使用
全局注册
在入口文件(如 main.js)中通过 Vue.component 注册:
import MyComponent from './MyComponent.vue'
Vue.component('MyComponent', MyComponent)
局部注册
在父组件中通过 import 引入并使用:
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
}
}
</script>
数据传递
Props 父传子
子组件声明接收的 props:
<script>
export default {
props: ['title', 'content']
}
</script>
父组件通过属性传递数据:
<template>
<ChildComponent title="标题" :content="dynamicContent" />
</template>
自定义事件子传父
子组件通过 $emit 触发事件:
this.$emit('update', newValue)
父组件监听事件:

<template>
<ChildComponent @update="handleUpdate" />
</template>
插槽(Slots)
默认插槽
子组件定义插槽:
<template>
<div>
<slot></slot>
</div>
</template>
父组件填充内容:
<ChildComponent>插槽内容</ChildComponent>
具名插槽
子组件定义多个插槽:
<template>
<div>
<slot name="header"></slot>
<slot name="footer"></slot>
</div>
</template>
父组件指定插槽位置:
<ChildComponent>
<template v-slot:header>头部内容</template>
<template v-slot:footer>底部内容</template>
</ChildComponent>
生命周期钩子
常用生命周期方法:

export default {
created() {
// 组件实例创建后调用
},
mounted() {
// DOM 挂载后调用
},
updated() {
// 数据更新导致 DOM 重新渲染后调用
},
destroyed() {
// 组件销毁前调用
}
}
样式作用域
通过 scoped 属性限定样式作用域:
<style scoped>
/* 仅作用于当前组件 */
</style>
动态组件
通过 <component> 标签和 is 属性实现动态切换:
<template>
<component :is="currentComponent"></component>
</template>
代码复用
Mixin 混入
定义混入对象:
const myMixin = {
methods: {
sharedMethod() {
console.log('共享方法')
}
}
}
组件中引入:
export default {
mixins: [myMixin]
}
Composition API
Vue 3 的 setup 函数:
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return { count }
}
}
</script>
最佳实践
- 组件命名采用 PascalCase(如
MyComponent.vue) - Prop 定义时指定类型和验证:
props: { title: { type: String, required: true } } - 复杂组件拆分为多个小组件
- 使用
v-model实现双向绑定:<template> <input v-model="inputValue" /> </template>






