系列文章目录
创作不易 拒绝白嫖 点个赞呗
关注我,带你走进前端的世界!!!
是什么
组合(composition)API的入口
setup 所处的生命周期
- beforeCreate -> use setup()
- created -> use setup()
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- errorCaptured -> onErrorCaptured
参数(props,context)
props
父组件传递的props
father
<template> <div> <child :dataFromFather="name" > </child> </div> </template> <script > import { ref } from "@vue/runtime-core"; import child from "./child.vue"; export default { components: { child, }, setup() { let name=ref('来自父组件的数据') return {name} }, }; </script> >
child
props:['dataFromFather'], setup(props, context) { console.log('dataFromFather=',props.dataFromFather) // 输出的是 '来自父组件的数据' }
context
- attrs
- slots
father
<child > <template v-slot:slot1> <h1>使用slot1</h1> </template> <template v-slot:slot2> <p>使用slot2</p> </template> </child>
child
// 定义slot1 和 slot2 <template> <div> <p>slot1</p> <slot name="slot1"></slot> </div> <div> <p>slot2</p> <slot name="slot2"></slot> </div> </template> <script> export default { setup(props, context) { console.log("1=", context.slots); onMounted: { console.log("2=", context.slots); } }, }; // 这里的打印结果 1=和2= 是一致的,打印的都是Proxy:slot1和slot2 !!! 若是father注释slot2的使用,那么只会打印proxy:slot1 </script>
child
<template> <div> <button @click="show">子组件</button> </div> </template> <script> export default { setup(props, context) { function show(){ context.emit('childShow','来自子组件') } return {show} }, }; </script>
father
<template> <div> <child @childShow='fatherShow'> </child> </div> </template> <script lang='ts'> import { onMounted } from "@vue/runtime-core"; import child from "./child.vue"; export default { components: { child, }, setup(props, context) { function fatherShow(data:any){ console.log(data) // 这里输出的是 ‘来自子组件 } return {fatherShow} }, }; </script>
使用渲染函数
import { h, ref, reactive } from 'vue' export default { setup() { const readersNumber = ref(0) const book = reactive({ title: 'Vue 3 Guide' }) // 请注意,我们需要在这里显式地暴露ref值 return () => h('div', [readersNumber.value, book.title]) } }