Vue3入门到精通-setup
2022-07-07 本文已影响0人
假笑boys
传送门
Vue3入门到精通 --ref 以及 ref相关函数
Vue3入门到精通 -reactive 以及reactive相关函数
是什么
组合(composition)API的入口
setup 所处的生命周期 (对比vue2.x版本生命周期)
选项式API | Hook inside setup |
---|---|
beforeCreate | Not need |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
update | onUpdated |
beforeDestroy | onBeforeUnmount |
destroyed | onUnmounted |
errorCaptured | onErrorCaptured |
-
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>