本文列举了 script-setup 比较常用的一些写法,更多内容可以移步至官方vue-script-setup查阅。
组件名 name
script-setup 无法指定当前组件的名字,所以使用的时候以文件名为主。
组件 components
在 script-setup 中导入任意的组件就可以直接在 template 中使用
<script setup>
import Foo from './Foo.vue'
import MyComponent from './MyComponent.vue'
</script>
<template>
<Foo />
<!-- kebab-case also works -->
<my-component />
</template>
动态组件使用
<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>
<template>
<component :is="Foo" />
<component :is="someCondition ? Foo : Bar" />
</template>
暴露组件的公共接口,父组件通过 ref 调用组件接口
<script setup>
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
</script>
指令 directive
导入指令的用法同 导入组件
<script setup>
import { directive as vClickOutside } from 'v-click-outside'
</script>
<template>
<div v-click-outside />
</template>
props
通过defineProps指定当前 props 类型的同时,获得上下文的 props 对象
在 script 中需要 props[key]引用,而 template 中可直接调用 key
<script setup>
import { defineProps } from 'vue'
// expects props options
const props = defineProps({
foo: String,
})
</script>
props 默认值
interface Props {
msg?: string
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello'
})
emit
通过 defineEmits 指定当前组件含有的触发事件 事件通过 defineEmits 返回的上下文 emit 进行触发
<script setup>
import { defineEmits } from 'vue'
// expects emits options
const emit = defineEmits(['update', 'delete'])
</script>
slots 和 attrs
<script setup>
import { useSlots, useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>
顶层 await 异步
script setup 内可以直接使用 await 异步,编译产物的setup()会自动加上async。
<script setup>
const post = await fetch(`/api/post/1`).then((r) => r.json())
</script>
import { withAsyncContext } from 'vue'
export default {
async setup() {
let __temp, __restore
const post =
(([__temp, __restore] = withAsyncContext(() =>
fetch(`/api/post/1`).then((r) => r.json())
)),
(__temp = await __temp),
__restore(),
__temp)
// current instance context preserved
// e.g. onMounted() will still work.
return { post }
}
}
自定义 template 绑定对象
<script setup="props">
export const foo = 1
export default {
props: ['bar']
}
</script>
<template>
<div>{{ foo + bar }}</div>
</template>
注:
<script setup></script> 遵循 setup 函数的规则,仅在组件加载时调用一次