而在 setup() 写的组合式 API 中,引入的组件必须在 components 内注册之后才能使用,否则无法正常引入。
3、组件数据传递
父组件给子组件传值时,需要 props 接收。setup( props, context )接收两个参数,props 接收传递的数据,使用 setup() 接收数据如下:
{{ a }} {{ b }}
而 script setup 语法糖接收 props 中的数据时,使用 defineProps 方法来获取,可以修改上述代码为:
{{ a }} {{ b }}
4、获取 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 自定义事件
5、对外暴露属性
script setup 语法糖的组件默认不会对外暴露任何内部声明的属性。如果有部分属性要暴露出去,可以使用 defineExpose。
子组件暴露属性:
{{msg}}
父组件引用子组件暴露的属性: