一.script setup
1.1定义
script setup是 Vue3 的一个新[语法糖,相比于普通的语法,简化了组合式API必须return的写法,拥有更好的运行时性能,具体详情参考Vue官方文档。
1.2使用
<script setup>
const name = '哈哈哈'
</script>
//等同于
<script>
setup(){
const name = '哈哈哈'
return {
name
}
}
</script>
1.3特点
- 声明的内容可以直接在模板中使用
- 自动注册组件
- 动态组件,应该使用动态的
:is
来绑定 - 必须使用
defineProps
和defineEmits
API 来声明 props 和 emits script setup
的组件是默认关闭的,需要defineExpose
明确要暴露的属性- 通过
useSlots
和useAttrs
两个辅助函数使用slots
和attrs
script setup
中可以使用顶层 await。结果代码会被编译成async setup()
二.setup()
setup
方法接受两个参数setup(props, context)
2.1props
是父组件传给组件的数据
2.2context
(上下文)
context中包含了一些常用属性:
attrs
表示由上级传向该组件,但并不包含在props
内的属性
<!-- parent.vue -->
<Child msg="hello world" :name="'child'"></Child>
/* child.vue */
export default {
props: { name: String },
setup(props, context) {
console.log(props) // {name: 'child'}
console.log(context.attrs) // {msg: 'hello world'}
},
}
emit
用于在子组件内触发父组件的方法
<!-- parent.vue -->
<Child @toggle="toggle"></Child>
/* child.vue */
export default {
setup(_, context) {
context.emit('toggle')
},
}
slots
用来访问被插槽分发的内容,相当于vm.$slots
<!-- parent.vue -->
<Child>
<template v-slot:header>
<div>header</div>
</template>
<template v-slot:content>
<div>content</div>
</template>
<template v-slot:footer>
<div>footer</div>
</template>
</Child>
/* child.vue */
export default {
setup(_, context) {
const { header, content, footer } = context.slots
return () => h('div', [h('header', header()), h('div', content()), h('footer', footer())])
},
}