Appearance
快速开始
本节介绍如何在本地搭建 Vue 单页应用。创建的项目将使用基于 Vite 的构建设置。
创建一个 Vue 应用
确保你安装了最新版本的 Node.js,然后在命令行中运行以下命令:
bash
npm create vue@latestbash
pnpm create vue@latestbash
yarn create vue@latestbash
bun create vue@latest这一指令将会安装并执行 create-vue,它是 Vue 官方的项目脚手架工具。你将会看到一些诸如 TypeScript 和测试支持之类的可选功能提示:
text
✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add an End-to-End Testing Solution? … No / Cypress / Playwright
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes
Scaffolding project in ./<your-project-name>...
Done.如果不确定是否要开启某个功能,你可以直接按下回车键选择 No。
安装依赖并运行
在项目被创建后,通过以下步骤安装依赖并启动开发服务器:
bash
cd <your-project-name>
npm install
npm run devbash
cd <your-project-name>
pnpm install
pnpm run devbash
cd <your-project-name>
yarn install
yarn devbash
cd <your-project-name>
bun install
bun run dev现在的 Vue 项目应该已经运行起来了!
发布生产版本
当你准备将应用发布到生产环境时,请运行:
bash
npm run buildbash
pnpm run buildbash
yarn buildbash
bun run build此命令会在 ./dist 文件夹中为你的应用创建一个生产环境的构建版本。关于将应用上线生产环境的更多内容,请阅读 部署指南。
通过 CDN 使用 Vue
你可以借助 script 标签直接通过 CDN 来使用 Vue:
html
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>通过 CDN 使用 Vue 时,不涉及“构建步骤”。这使得设置更加简单,并且可以用于增强静态的 HTML 或与后端框架集成。但是,你将无法使用单文件组件 (SFC) 语法。
所有顶层 API 都以属性的形式暴露在了全局的 Vue 对象上。这里有一个使用全局构建版本的例子:
html
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app">{{ message }}</div>
<script>
const { createApp, ref } = Vue
createApp({
setup() {
const message = ref('Hello vue!')
return {
message
}
}
}).mount('#app')
</script>使用 ES 模块构建版本
现代浏览器大多都已原生支持 ES 模块。因此我们可以像这样通过 CDN 以及原生 ES 模块使用 Vue:
html
<div id="app">{{ message }}</div>
<script type="module">
import { createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
createApp({
setup() {
const message = ref('Hello vue!')
return {
message
}
}
}).mount('#app')
</script>启用 Import maps
为了使 Vue 能够在没有构建步骤的情况下工作,我们需要启用浏览器对 ES 模块的支持。这可以通过在 HTML 中添加一个 importmap 来实现:
html
<script type="importmap">
{
"imports": {
"vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
}
}
</script>
<div id="app">{{ message }}</div>
<script type="module">
import { createApp, ref } from 'vue'
createApp({
setup() {
const message = ref('Hello vue!')
return {
message
}
}
}).mount('#app')
</script>拆分模块
随着逻辑的增加,我们可以将代码拆分成单独的 JavaScript 文件,以便于维护:
index.html:
html
<!-- index.html -->
<script type="importmap">
{
"imports": {
"vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
}
}
</script>
<div id="app"></div>
<script type="module">
import { createApp } from 'vue'
import MyComponent from './my-component.js'
createApp(MyComponent).mount('#app')
</script>my-component.js:
js
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return { count }
},
template: `<div>Count is: {{ count }}</div>`
}