实现.vue文件
创建Vue单文件组件
Vue单文件组件(.vue文件)是Vue.js框架的核心特性之一,它将模板、脚本和样式封装在一个文件中。一个典型的.vue文件结构包含三个部分:<template>、<script>和<style>。
<template>
<div class="example">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
.example {
color: red;
}
</style>
配置开发环境
使用Vue单文件组件需要配置构建工具。Vue CLI是官方推荐的脚手架工具,可以快速搭建Vue项目环境。
安装Vue CLI:
npm install -g @vue/cli
创建新项目:
vue create my-project
组件基本结构
<template>部分包含组件的HTML模板,必须有一个根元素。模板中可以使用Vue的指令和插值语法。
<script>部分包含组件的JavaScript代码。通常导出一个Vue组件选项对象,包含data、methods、props等选项。
<style>部分包含组件的CSS样式。添加scoped属性可以使样式只作用于当前组件。
使用组件
在其他组件中使用自定义组件需要先导入并注册:
<template>
<div>
<ExampleComponent />
</div>
</template>
<script>
import ExampleComponent from './ExampleComponent.vue'
export default {
components: {
ExampleComponent
}
}
</script>
添加TypeScript支持
Vue 3对TypeScript有更好的支持。要使用TypeScript,可以修改<script>标签:
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
data() {
return {
message: 'Hello Vue with TS!'
}
}
})
</script>
单文件组件高级特性
Vue单文件组件支持许多高级特性:
- 使用
<script setup>语法糖简化组合式API代码 - 使用CSS预处理器如Sass/SCSS、Less
- 自定义块处理文档或其他特定需求
- 热重载开发体验
构建与打包
Vue单文件组件需要构建工具处理。Vue CLI内部使用webpack,也可以配置使用Vite等现代构建工具。构建后的组件会被编译为标准JavaScript代码,可在浏览器中运行。
构建生产版本:
npm run build






