单文件组件
什么是单文件组件? 简称SFC,将模版(template)、逻辑(script)、样式(style)整合在一个文件中,通常以`.vue`的形式存在。 简化组件开发和管理,使得代码更加清晰、模块化、便于维护
结构
模版
- 使用
<template>标签定义 - 用来描述HTTML结构和内容
<template>
<div class="my-component">
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
</template>
脚本
- 使用
<script>标签定义 - 包含组件的逻辑代码,通常是JavaScript或者TypeScript
<script>
export default {
data() {
return {
title: 'Hello, Vue!',
message: 'This is a single file component.'
};
}
};
</script>
样式
- 使用
<stype>标签定义 - 定义组件css样式,可以选择是否使用scoped来限定样式作用范围
<style scoped>
.my-component {
font-family: Arial, sans-serif;
}
</style>
单文件组件优点
模块化
将模版、逻辑、样式整合在一个文件中,方便组件开发、阅读和维护。
作用域样式
使用scoped属性,组件的样式仅作用于当前组件,避免样式污染其他组件
增强可读性
将相关的代码放在一起,使得代码结构更加清晰,增强了可读性
代码复用
通过创建独立组件,可以方便的在不同的项目或者应用中重用代码
Vue cli的支持
提供对单文件组件的强大支持,可以轻松创建、贬义词和打包单文件组件
使用
通常情况下,使用 Vue CLI 或 Vue Loader 来处理单文件组件。它们可以将 .vue 文件编译成标准的 JavaScript 文件,供浏览器运行。
- 组件示例
<!-- MyComponent.vue -->
<template>
<div class="greeting">
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, World!'
};
}
};
</script>
<style scoped>
.greeting {
color: blue;
}
</style>
组件使用:
// 在 App.vue 或其他组件中使用
<template>
<div id="app">
<MyComponent />
</div>
</template>
<script>
import MyComponent from './components/MyComponent.vue';
export default {
components: {
MyComponent
}
};
</script>