Skip to content
第 1 章 前端 ⏱ 10 分钟阅读

第 1 章:Vue 3 入门 ​

学习目标 ​

  • 用 Vite 创建一个 Vue 3 项目
  • 理解 main.ts 和 App.vue 的关系
  • 写出第一个按钮计数器
  • 避开 <script setup> 的 3 个常见坑

一、初始化项目 ​

bash
# Node ≥ 18
npm create vue@latest my-app   # 交互式,本教程手写
cd my-app
npm install
npm run dev                    # 默认 http://localhost:5173

手动最小结构:

my-app/
├─ index.html
├─ src/
│  ├─ main.ts          # 入口文件
│  └─ App.vue
├─ vite.config.ts
└─ package.json

二、三个核心文件 ​

2.1 index.html ​

html
<!DOCTYPE html>
<html lang="zh">
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

2.2 main.ts ​

ts
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')   // 挂载到 #app

2.3 App.vue(单文件组件) ​

vue
<script setup lang="ts">
import { ref } from 'vue'

const count = ref(0)            // ⚠️ 状态必须用 ref/reactive 包裹
const inc = () => count.value++ // 模板里写 count,这里要 .value
</script>

<template>
  <button @click="inc">点击 {{ count }} 次</button>
</template>

⚠️ 坑 1:ref 在 <script> 里要 .value,在 <template> 里不用。 ⚠️ 坑 2:lang="ts" 别忘了,否则 <script setup> 里的 TS 会报错。

三、文件命名与目录约定 ​

文件命名示例
组件大驼峰UserCard.vue
工具小驼峰useRequest.ts
目录小驼峰src/views/
静态资源小写中划线logo-dark.svg

.vue 文件必须大驼峰,否则以 <my-button> 形式引用时大小写会乱。

四、第一个完整示例 ​

vue
<!-- src/App.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import HelloWorld from './components/HelloWorld.vue'

const msg = ref('Hello Vue 3')
</script>

<template>
  <h1>{{ msg }}</h1>
  <HelloWorld :name="msg" />
</template>
vue
<!-- src/components/HelloWorld.vue -->
<script setup lang="ts">
defineProps<{ name: string }>()   // ⚠️ 运行时声明 props
</script>

<template>
  <p>欢迎,{{ name }}!</p>
</template>

五、运行与热更新 ​

bash
npm run dev         # 启动 dev server,默认 5173 端口
npm run build       # 生产构建,产物在 dist/
npm run preview     # 本地预览构建产物

Vite 默认开启 HMR,改代码保存即刷新,无需手动 reload。

六、本章小结 ​

要点关键
创建项目npm create vue@latest 或手写最小三件套
入口createApp(App).mount('#app')
SFC<script setup lang="ts"> + <template> + <style>
响应式ref() 包裹基本类型,.value 取值
命名组件大驼峰,目录小驼峰

动手练习 ​

  1. 跑通计数器:复制第 2 节的代码,点 5 次按钮,数字正确累加
  2. 加个重置:在 <button> 旁边加一个 清零 按钮,调用 count.value = 0
  3. 拆分组件:把计数器拆成 Counter.vue 子组件,父组件控制传入初始值

下一章:第 2 章:模板语法 →

本站基于 VitePress 构建 · 由 StackHub 团队维护