setup
setup中包含两个参数 props 和 context
props
props 可以获取父组件传递过来的值,需要注册选项props接收参数后,才能在setup中的props中获取。
解构props的值变成非响应式数据。凡是可以通过toRef和toRefs包裹之后在进行解构,就可以保持数据的响应式变化。
context
context参数中包含了多个属性
const { attrs, slots, emit, expose } = context
attrs
attrs可以获取没有在props中注册的数据
slots
emit
子组件
setup(props, context) {
context.emit('customEvent', () => console.log('收到了'))
}
父组件
<Children @customEvent="handleEvent" />
setup() {
const handleEvent = (func) => {
console.log(func)
func()
}
}
expose
可以暴露出属性给父组件,父组件通过ref获取子组件中暴露的数据。
子组件
expose({ hworld: '我是helloWorld暴露出来的组件' })
父组件
<Children :customValue="value" ref="childrenRef" />
setup(props, context) {
const childrenRef = ref(null)
// console.log(context.attrs, 'app组件的attrrs')
onMounted(() => {
console.log(childrenRef.value, 'childrenRef')
})
return { childrenRef }
}