vue3中的单文件组件<script setup>详解
一、相比普通script语法的优势
<script setup>
是在单文件组件 (SFC)
中使用组合式 API
的编译时语法糖
。相比于普通的 <script> 语法
,它具有更多优势
- 更少的样板内容,更简洁的代码
- 能够使用纯 Typescript 声明 props 和抛出事件。
- 更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。
- 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。
二、基本语法
- 要使用这个语法,需要将 setup attribute 添加到
<script> 代码块上
<script setup>
console.log('hello script setup')
</script>
- 里面的代码会
被编译成组件 setup() 函数的内容
。这意味着与普通的<script>
只在组件被首次引入
的时候执行一次
不同,<script setup>
中的代码会在每次
组件实例被创建
的时候执行。
顶层的绑定会被暴露给模板
- 当使用
<script setup>
的时候,任何在<script setup> 声明的顶层的绑定
(包括变量,函数声明,以及 import 引入的内容) 都能在模板
中直接使用
<script setup>
// 变量
const msg = 'Hello!'
// 函数
function log() {
console.log(msg)
}
</script>
<template>
<div @click="log">{
{
msg }}</div>
</template>
- import 导入的内容也会以同样的方式暴露。意味着
可以在模板表达式中直接使用导入的 helper 函数
,并不需要通过 methods 选项来暴露它:
<script setup>
import {
capitalize } from './helpers'
</script>
<template>
<div>{