Vue3 setup 执行时机和 参数props context

一、执行时机

在beforecreate生命周期函数前执行一次,且this为undefined

二、setup参数

1、props:值为对象,组件外部传递过来,且组件内部通过props:[]接受的值

a、外部组件传递

<Demon msg="Hello" :num="10"/>

b、且内部组件接受

export default {
    name:'Demon',
    // 接收 外部组件传递过来的值
    props:['msg', 'num'],
    setup(props, context){
        console.log(props.num)
        const person = reactive({
            name: 'jojo',
            age: 8,
        })
        return {
            person,
        }
    },
}

2、context

a、attr

1)、值为对象,外部组件传递过来的值且没有被本组件的porps:[] 属性声明接收

2)、语法

console.log(context.attrs)

b、emit

1)、触发事件,子组件传递参数给父组件,在子组件中触发事件则调用父组件中的方法

2)、语法

父组件定义事件

<Demon @age="showAge" msg="Hello" :num="10"></Demon>

父组件实现方法

function showAge(value) {
    alert(`年龄:${value}` )
    // console.log(value)
}

子组件声明emits:[],与props类似

emits:['age'],

子组件通过click触发事件

// 传递参数
function ageButton() {
    context.emit('age', person.age)
}

 b、slot

1)、收到插槽的内容,相当于this.$slots

2)、语法

定义:父组件插槽

<template v-slot:qwe>
    <span>123</span>
</template>

使用插槽

<slot name="qwe"></slot>

 

posted @ 2025-01-09 16:34  市丸银  阅读(73)  评论(0)    收藏  举报