星球的眼睛 发表于 2025-3-12 11:51:28

vue3-setup的实行机遇(早于beforeCreate this为undefined)与传递参数(pro

1.前言

        setup函数是组合式API的一部分,用于组件创建之前实行逻辑,新的组合式API入口点,用于组件创建前实行逻辑,setup函数接收两个参数props与context。props包含了传递给子组件的所有属性。context包含attrs,slots,emit.
        setup实行的机遇
        在beforeCreate前实行一次,this是undefined.
        setup参数
        props: 值为对象,包含组件外部传递过来,并且组件内部声明接收了的属性。
        context:上下文对象
        attrs:值为对象,组件外部传递但是没有在props设置接收中声明的属性,this.$attrs.
        slots:收到的插槽内容,this.$slots.
        emit:分发自定义事件函数,this.$emit.
2.vue3中的props传参

父组件中利用子组件:参数传递给子组件。
<!-- ParentComponent.vue -->
<template>
<div>
    <ChildComponent :name="parentName" :age="parentAge" />
</div>
</template>

<script>
import { defineComponent, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default defineComponent({
name: 'ParentComponent',
components: {
    ChildComponent
},
setup() {
    const parentName = ref('messi');
    const parentAge = ref(15);

    return {
      parentName,
      parentAge
    };
}
});
</script>
子组件利用setup函数接收参数
<!-- ChildComponent.vue -->
<template>
<div>
    <p>用户名字: {{ name }}</p>
    <p>用户年龄: {{ age }}</p>
</div>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
name: 'ChildComponent',
props: {
    name: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      required: true
    }
},
setup(props) {
    // 在这里可以使用props.name 和 props.age
    console.log(props.name, props.age);
    return {
      // 返回的数据可以在模板中使用
    };
}
});
</script>
3.context对象emit方法触发自定义事件

父组件
<template>
<div>
    <ChildComponent :msg="message" @child-click="handleChildClick" />
</div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
components: {
    ChildComponent
},
setup() {
    const message = ref('Hello from Parent');
    const handleChildClick = (childMessage) => {
      console.log(`Received from child: ${childMessage}`);
    };

    return {
      message,
      handleChildClick
    };
}
};
</script>
子组件

<template>
<div>
    <p>{{ msg }}</p>
    <button @click="sendMessageToParent">Click me</button>
</div>
</template>

<script>
export default {
props: {
    msg: String
},
setup(props, context) {
    const sendMessageToParent = () => {
      context.emit('child-click', 'Hello from Child');
    };

    return {
      sendMessageToParent
    };
}
};
</script>
   context 对象的 emit 方法被用来触发一个自定义事件 child-click,并将消息从子组件传递给父组件。父组件通过监听 child-click 事件来接收子组件传递的消息,并在控制台中打印出来。
        context 对象的其他属性,如 attrs 和 slots,也可以在 setup 函数中利用,分别用于访问组件的非prop属性和插槽内容。expose 方法可以用来显式地袒露组件实例上的属性或方法,使得父组件可以通过模板引用访问这些属性或方法。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: vue3-setup的实行机遇(早于beforeCreate this为undefined)与传递参数(pro