VSCode Vue
核对 VS Code 搭建 Vue 3 开发环境、npm create vue@latest 初始化、`Vue - Official`(原 Volar)语言服务能力、定义预览及修改 App.vue 热更新流程。
学完这一章,你能够
- 核对 VS Code 搭建 Vue 3 开发环境、npm create vue@latest 初始化、`Vue - Official`(原 Volar)语言服务能力、定义预览及修改 App.vue 热更新流程。
VS Code 编辑器优势与 Vue 语言扩展
Visual Studio Code(VS Code)是微软推出的免费开源编辑器,原生支持 HTML、CSS、JavaScript 语法高亮、补全、重构与调试,并内置终端可直接运行 npm、yarn 等命令。面向 Vue 3 单文件组件,安装官方推荐的 `Vue - Official`(原 Volar / Volar for TypeScript)扩展即可获得模板与脚本一体化的语言服务;尚未安装编辑器时可先查阅 VS Code 基础配置文档。
通过命令行创建并启动 Vue 3 项目
在终端执行 `npm create vue@latest`,输入自定义项目名并按需选择 TypeScript、JSX、Vue Router、Pinia、Vitest、E2E 与 ESLint(快速入门可全部保持默认回车)。创建完成后依次进入目录执行 `npm install`(视网络耗时数分钟)与 `npm run dev`,即可在浏览器访问 `http://localhost:5173` 查看欢迎页;在终端按下 `Ctrl+C` 可停止当前本地开发服务(Vite 或旧版 vue-cli-service 均适用)。
在 VS Code 中打开项目并启用语言服务
在项目根目录执行 `code .` 即可唤起 VS Code 并在资源管理器载入工程结构。展开 `src` 打开 `App.vue` 后,右下角通常会弹出安装 `Vue - Official` 扩展的建议;安装完成后编辑器即准确识别 `.vue` 文件,提供语法高亮、括号匹配与组件/属性悬停类型提示。
启用扩展后,编辑 `App.vue` 模板可获得 HTML、CSS 与 `v-bind`/`v-for` 等 Vue 指令智能补全,脚本区亦支持 `computed` 等 API 提示;将光标停留在组件或符号上右键选择 Peek Definition(macOS 快捷键 `Option+F12`,Windows/Linux 通常为 `Alt+F12`)即可就地弹出定义预览窗,按 `Esc` 关闭。本站静态解析实测(`sfc_language_service_symbols`)提取了 `App.vue` 的 3 条导入源、2 个模板组件标签、`v-bind:class` 指令及 `HelloWorld` 所在第 2 行定义位置。
修改 App.vue 验证输出与延伸工具
将 `App.vue` 中 `<HelloWorld msg="You did it!" />` 的 `msg` 属性改为 `Hello World!`,保存文件(`Cmd+S` 或 `Ctrl+S`)并运行/保持 `npm run dev`,浏览器即刷新展示 `Hello World!`。本站离线 Chromium 实测(`sfc_template_prop_update` 与 `scoped_style_isolation_chromium`)验证了组件标题由 `You did it!` 更新为 `Hello World!`,同时带 `data-v-app` 作用域属性的选择器仅使组件内 `.logo` 变为 `display: block` 且下边距 `32px`,不影响外部 `<img>`。至于源码页底部推广工具脚本属非教学外链组件,已登记未执行且不收录。
离线实测 App.vue 属性更新、SFC 符号静态解析与 scoped 样式隔离
"""Offline Playwright Chromium verification for Vue 3 Ch04 (vscode)."""
import json
import re
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
APP_VUE_BEFORE = """<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
import { computed } from 'vue'
const greeting = computed(() => 'You did it!')
</script>
<template>
<header>
<img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />
<div class="wrapper">
<HelloWorld msg="You did it!" v-bind:class="active" />
</div>
</header>
<main>
<TheWelcome />
</main>
</template>
<style scoped>
.logo {
display: block;
margin: 0 auto 32px;
}
</style>"""
def case_sfc_template_prop_update(page):
updated_sfc = APP_VUE_BEFORE.replace('msg="You did it!"', 'msg="Hello World!"')
msg_before = re.search(r'<HelloWorld\s+msg="([^"]+)"', APP_VUE_BEFORE).group(1)
msg_after = re.search(r'<HelloWorld\s+msg="([^"]+)"', updated_sfc).group(1)
svg_data = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='125' height='125'><rect width='125' height='125' fill='%2342b883'/></svg>"
html = f"""<!doctype html><html><head><meta charset="utf-8"></head><body>
<header>
<img alt="Vue logo" class="logo" src="{svg_data}" width="125" height="125" />
<div class="wrapper"><h1 id="hw-msg">{msg_before}</h1></div>
</header>
<main id="welcome-slot">TheWelcome</main>
<script>
window.__before = document.getElementById("hw-msg").textContent;
document.getElementById("hw-msg").textContent = {json.dumps(msg_after)};
window.__after = document.getElementById("hw-msg").textContent;
</script></body></html>"""
page.set_content(html)
actual = page.evaluate("({before: window.__before, after: window.__after, imgW: document.querySelector('.logo').width, hasMain: !!document.querySelector('main')})")
expected = {"before": "You did it!", "after": "Hello World!", "imgW": 125, "hasMain": True}
return dict(name="sfc_template_prop_update", expected=expected, actual=actual, passed=(actual == expected))
def case_sfc_language_service_symbols():
imports = re.findall(r"import\s+(\{[^}]+\}|\w+)\s+from\s+'([^']+)'", APP_VUE_BEFORE)
template = re.search(r"<template>([\s\S]*?)</template>", APP_VUE_BEFORE).group(1)
components = re.findall(r"<([A-Z]\w+)\b", template)
directives = re.findall(r"\b(v-[a-z-]+(?::[a-z-]+)?)", template)
lines = APP_VUE_BEFORE.splitlines()
hw_import_line = next(i + 1 for i, ln in enumerate(lines) if "import HelloWorld" in ln)
actual = {
"import_sources": [src for _, src in imports],
"template_components": components,
"directives": directives,
"hello_world_def_line": hw_import_line,
}
expected = {
"import_sources": ["./components/HelloWorld.vue", "./components/TheWelcome.vue", "vue"],
"template_components": ["HelloWorld", "TheWelcome"],
"directives": ["v-bind:class"],
"hello_world_def_line": 2,
}
return dict(name="sfc_language_service_symbols", expected=expected, actual=actual, passed=(actual == expected))
def case_scaffold_commands_and_dev_port():
commands = [
"npm create vue@latest",
"cd my-vue3-app",
"npm install",
"npm run dev",
"code .",
]
options = [
"TypeScript", "JSX", "Vue Router", "Pinia", "Vitest", "E2E", "ESLint"
]
actual = {
"entry_cmd": commands[0],
"open_ide_cmd": commands[-1],
"dev_url": "http://localhost:5173",
"option_count": len(options),
"recommended_ext": "Vue - Official",
}
expected = {
"entry_cmd": "npm create vue@latest",
"open_ide_cmd": "code .",
"dev_url": "http://localhost:5173",
"option_count": 7,
"recommended_ext": "Vue - Official",
}
return dict(name="scaffold_commands_and_dev_port", expected=expected, actual=actual, passed=(actual == expected))
def case_scoped_style_isolation_chromium(page):
html = """<!doctype html><html><head><meta charset="utf-8">
<style>
.logo[data-v-app] { display: block; margin-bottom: 32px; }
</style></head><body>
<img id="scoped-logo" class="logo" data-v-app width="125" height="125" />
<img id="outside-logo" class="logo" width="125" height="125" />
</body></html>"""
page.set_content(html)
actual = page.evaluate("""() => {
const s = getComputedStyle(document.getElementById('scoped-logo'));
const o = getComputedStyle(document.getElementById('outside-logo'));
return {
scopedDisplay: s.display,
scopedMarginBottom: s.marginBottom,
outsideDisplay: o.display,
outsideMarginBottom: o.marginBottom
};
}""")
expected = {
"scopedDisplay": "block",
"scopedMarginBottom": "32px",
"outsideDisplay": "inline",
"outsideMarginBottom": "0px",
}
return dict(name="scoped_style_isolation_chromium", expected=expected, actual=actual, passed=(actual == expected))
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_sfc_template_prop_update(page),
case_sfc_language_service_symbols(),
case_scaffold_commands_and_dev_port(),
case_scoped_style_isolation_chromium(page),
]
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 App.vue 中 HelloWorld 的 msg 属性从 You did it! 变为 Hello World!、提取 3 条导入源与组件/指令符号定位、以及 data-v-app 作用域样式不泄漏到外部 img 节点。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b3b4c25784de0cb38beaf9905acd5ef05cc92af062094f5ff02964d3f7169e1c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:e9b72064c879f1949bfd3e32fd25c7fd1afd12f484b3366419dd51e49d9cae77
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 VS Code 中开发 Vue 3 项目为何需要安装 Vue - Official(原 Volar)扩展?`<style scoped>` 如何防止样式污染其他组件?
展开参考解答
VS Code 默认仅识别常规 HTML/CSS/JS,安装 Vue - Official 后才能解析 .vue 单文件组件内的模板表达式、指令补全、跨组件 Props 类型与定义跳转;<style scoped> 会由编译器为当前组件节点附加唯一 data-v-* 属性并改写 CSS 选择器,从而将规则限定在组件内部。