单文件组件语法定义
VueAPI 参考
单文件组件语法定义 {#sfc-syntax-specification}
总览 {#overview}
一个 Vue 单文件组件 (SFC),通常使用 *.vue 作为文件扩展名,它是一种使用了类似 HTML 语法的自定义文件格式,用于定义 Vue 组件。一个 Vue 单文件组件在语法上是兼容 HTML 的。
每一个 *.vue 文件都由三种顶层语言块构成:<template>、<script> 和 <style>,以及一些其他的自定义块:
vue
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data() {
return {
msg: 'Hello world!'
}
}
}
</script>
<style>
.example {
color: red;
}
</style>
<custom1>
This could be e.g. documentation for the component.
</custom1>
相应语言块 {#language-blocks}
<template> {#template}
-
每个
*.vue文件最多可以包含一个顶层<template>块。 -
语块包裹的内容将会被提取、传递给
@vue/compiler-dom,预编译为 JavaScript 渲染函数,并附在导出的组件上作为其render选项。
<script> {#script}
- 每个
*.vue文件最多可以包含一个<script>块。(使用 [`
`lang` 在任意块上都能使用,比如我们可以在 `<style>` 标签中使用 [Sass](https://sass-lang.com/) 或是 `<template>` 中使用 [Pug](https://pugjs.org/api/getting-started.html):
```vue-html
<template lang="pug">
p {{ msg }}
</template>
<style lang="scss">
$primary-color: #333;
body {
color: $primary-color;
}
</style>
注意对不同预处理器的集成会根据你所使用的工具链而有所不同,具体细节请查看相应的工具链文档来确认:
src 导入 {#src-imports}
如果你更喜欢将 *.vue 组件分散到多个文件中,可以为一个语块使用 src 这个 attribute 来导入一个外部文件:
vue
<template src="./template.html"></template>
<script src="./script.js"></script>
请注意 src 导入和 JS 模块导入遵循相同的路径解析规则,这意味着:
- 相对路径需要以
./开头 - 你也可以从 npm 依赖中导入资源
vue
<!-- 从所安装的 "todomvc-app-css" npm 包中导入一个文件 -->
<style src="todomvc-app-css/index.css" />
src 导入对自定义语块也同样适用:
vue
<unit-test src="./unit-test.js">
</unit-test>
:::warning 注意
在 src 中使用别名时,不要以 ~ 开头,后面的任何内容都会被解释为模块请求。这意味着你可以引用 node 模块中的资源:
vue
<img src="~some-npm-package/foo.png">
:::
注释 {#comments}
在每一个语块中你都可以按照相应语言 (HTML、CSS、JavaScript 和 Pug 等等) 的语法书写注释。对于顶层注释,请使用 HTML 的注释语法 <!-- comment contents here -->
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
