Vue3入门到精通-setup
【摘要】 是什么组合(composition)API的入口 setup 所处的生命周期beforeCreate -> use setup()created -> use setup()beforeMount -> onBeforeMountmounted -> onMountedbeforeUpdate -> onBeforeUpdateupdated -> onUpdatedbeforeDestr...
是什么
组合(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>
-
emit
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])
}
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)