顶层的绑定会被暴露给模板
<script setup lang="ts">
// 引入的函数
import { capitalize } from './helpers'
// 变量
const msg = 'Hello!'
// 函数
function log() {
console.log(msg)
}
// 响应式变量
const count = ref(0)
</script>
<template>
<div @click="log">{{ msg }}</div>
<div>{{ capitalize('hello') }}</div>
<button @click="count++">{{ count }}</button>
</template>
使用组件
普通组件
<script setup lang="ts">
import MyComponent from './MyComponent.vue'
</script>
<template>
<MyComponent />
</template>
动态组件
<script setup lang="ts">
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>
<template>
<component :is="Foo" />
<component :is="someCondition ? Foo : Bar" />
</template>
命名空间组件
<script setup>
import * as Form from './form-components'
</script>
<template>
<Form.Input>
<Form.Label>label</Form.Label>
</Form.Input>
</template>
组件的属性和事件
<script setup>
const props = defineProps({
foo: String
})
const emit = defineEmits(['change', 'delete'])
// setup code
</script>
声明可被父组件访问的方法或变量
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
</script>
useSlots 和 useAttrs
<script setup>
import { useSlots, useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>
使用类型声明时的默认 props 值
const props = defineProps<{
foo: string
bar?: number
}>()
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})