学习真的是一件很累的事情,更何况有这么多杂七杂八的事情
唉唉,莎了我吧
Vue3 构建
Vue3 每一次构建新项目时,都会从 npm 上拉取模板。
在 VS Code 中按:
CTRL + ~
打开终端,然后输入:
npm create vite@latest vue -- --template vue-ts
解释一下这条命令:
create vite@latest:使用最新版本的 Vite 创建项目vue:项目文件夹名--template vue-ts:使用 Vue + TypeScript 模板
中途会问:
- 是否使用实验性功能 → 选择
NO - 是否下载并运行 → 选择
YES
然后它会自动在当前文件夹生成一个完整的 Vue3 项目。
每次启动项目,都在项目根目录输入命令:npm run dev 启动本地开发服务器
项目入口结构
生成后,项目默认打开的是 index.html。
里面有一行关键代码:
<script type="module" src="/src/main.ts"></script>
这句话非常重要。
意思是:
浏览器加载 main.ts 作为整个应用的入口模块。
也就是说:
真正的程序逻辑从 main.ts 开始。
关于一些基础知识
在main.ts中我们会看到一些代码,我将代码及注释放到这里:
ts
import { createApp } from 'vue'
// 从 vue 模块中拿出 createApp 这个命名导出
import './style.css'
// 引入全局样式
import App from './App.vue'
// 从 App.vue 中拿出默认导出的组件
createApp(App).mount('#app')
// 创建一个 Vue 应用实例
// 并把它挂载到 index.html 里的 #app 上
也就是说,从 app.vue 中拿东西出来,插到 index.html 中的#app这个组件上面
从app.vue中我们会看到三段代码:
vue
<script setup lang="ts">
</script>
<template>
</template>
<style scoped>
</style>
<script setup>:逻辑<template>:结构(HTML)<style scoped>:样式
在 Vue3 中使用 <script setup> 是推荐写法,它是 Composition API 的语法糖。
<style>加上 scoped 后,这里的样式只对当前组件生效,不会跑到外面去乱窜(防止样式污染)。
样例:
vue
<script setup lang="ts">
defineOptions({ name: 'App' });
</script>
<template>
<div class="title">
<h1>这是一个标题</h1>
</div>
</template>
<style scoped>
.title {
background-color: pink;
box-shadow: 0 0 10px;
padding: 20px;
border-radius: 10px;
}
</style>
一个 .vue 文件在编译后,本质上会变成一个 JS 模块,模块对外输出一个值------通常就是"组件对象"。
也就是说,做网站就像拼积木一样,每一个 Vue 文件都是一块积木
最后拼好之后,Vue 会把整棵组件树插入到 HTML 里的那个 #app 容器里。
以下是一段简单的代码,在网页中显示了一块信息页

一份简单的样例
这是我的部分文件树:
D:
index.html
src
│ App.vue
│ main.ts
│ style.css
│
├─assets
│ vue.svg
│
└─components
IsMe.vue
我将 IsMe.vue 拼图插入到 App.vue 中,
IsMe.vue:
vue
<script setup lang="ts">
defineOptions({ name: 'personPage' });
</script>
<template>
<div class="background">
<h1>This Is My Homepage</h1>
<div class="inf">这就是信息页</div>
</div>
</template>
<style scoped>
.background {
background-color: pink;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
.background h1 {
text-align: left;
}
.inf {
box-shadow: 0 0 5px;
color: purple;
font-size: 50px;
border-radius: 20px;
}
</style>
App.vue
vue
<script setup lang="ts">
import PersonPage from './components/IsMe.vue';
</script>
<template>
<PersonPage /> <!--在这里插入IsMe.vue组件-->
</template>
<style scoped></style>
import是把组件模块引入<PersonPage />是使用组件- 在
<script setup>中 import 后可以直接使用,不需要额外注册
index.html
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>vue</title>
</head>
<body>
<div id="app"></div> <!--在这里插入App.vue组件-->
<script type="module" src="/src/main.ts"></script>
</body>
</html>
这里的 #app 只是一个挂载容器。
真正的页面结构全部来自 Vue。
总结
Vue3 的工作流程就是:
- 写小积木(Components)。
- 在大积木里组装小积木(App.vue)。
- 通过
main.ts把大积木挂到index.html。
像这样拼积木,一份项目就拼出来了