script setup 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的 script 语法,具有以下特点:
- 更少的样板内容,更简洁的代码。
- 能够使用纯 TypeScript 声明 props 和自定义事件。
- 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
- 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。
属性和方法无需返回,可直接使用
使用 script setup 语法糖时,内部的属性或方法可以直接使用,无需 return 返回;引入子组件可以自动注册,无需 components 注册可直接使用等等,接下来介绍 script setup 语法糖具体使用以及与 setup() 函数的区别。
setup() 来写组合式 API 时,内部定义的属性和方法,必须使用 return 暴露到上下文,外部才能够使用,否则就会报错,写法为:
<template>
{{num}}
</template>
<script>
import {ref} from 'vue'
export default {
setup(){
const num = ref(1)
return{ num }
}
}
</script>
使用 script setup 语法糖,可以简化上述代码为:
<template>
{{num}}
</template>
<script setup>
import {ref} from 'vue'
const num = ref(1)
</script>
组件自动注册
在 script setup 语法糖中,引入的组件可以自动注册,不需要再通过 components 进行注册,而且无法指定当前组件的名字,会自动以文件名为主,省去了 name 属性。
<template>
<Child></Child>
</template>
<script setup>
import Child from './Child.vue'
</script>
而在 setup() 写的组合式 API 中,引入的组件必须在 components 内注册之后才能使用,否则无法正常引入。
组件数据传递
父组件给子组件传值时,需要 props 接收。setup( props, context )接收两个参数,props 接收传递的数据,使用 setup() 接收数据如下:
<template>
{{ a }} {{ b }}
</template>
<script>
import { toRefs } from "vue"
export default {
setup(props,context){
const { a,b } = toRefs(props)
return {
a,
b
}
}
}
</script>
而 script setup 语法糖接收 props 中的数据时,使用 defineProps 方法来获取,可以修改上述代码为:
<template>
{{ a }} {{ b }}
</template>
<script setup>
import { toRefs } from "vue"
const props = defineProps({
a: String,
b: String
})
const { a, b } = toRefs( props )
</script>
获取 attrs、slots 和 emits
setup( props, context )接收两个参数,context 上下文环境,其中包含了属性、插槽、自定义事件三部分。
setup() 内获取如下:
setup(props,context){
const { attrs, slots, emit } = context
// attrs 获取组件传递过来的属性值,
// slots 组件内的插槽
// emit 自定义事件 子组件
}
使用 script setup 语法糖时,
- useAttrs 方法 获取 attrs 属性
- useSlots 方法获取 slots 插槽
- defineEmits 方法获取 emit 自定义事件
<script setup>
import { useAttrs, useSlots } from 'vue'
const slots = useSlots();
const attrs = useAttrs();
const emits = defineEmits(['getChild']);
</script>
对外暴露属性
使用 script setup 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 script setup 中声明的绑定。
可以通过 defineExpose 编译器宏来显式指定在 script setup 组件中要暴露出去的属性,若不使用 defineExpose 则获取不到当前引用的组件实例变量、方法
<template>
{{b}}
</template>
<script setup>
import { ref, defineExpose } from 'vue'
const a = 1;
const b = ref(2)
defineExpose({
a,
b
});
</script>