Vue3 中 Setup 函数如何使用 props 和 context 参数

2025-01-10 19:35:32   小编

Vue3 中 Setup 函数如何使用 props 和 context 参数

在 Vue3 的开发中,Setup 函数是一个非常重要的新特性,它为组件逻辑的编写带来了全新的方式。其中,props 和 context 参数的运用,更是 Setup 函数发挥强大功能的关键部分。

首先来看看 props 参数。props 主要用于在父组件向子组件传递数据。在 Setup 函数中使用 props,需要在组件选项中进行声明。例如,我们创建一个子组件,在子组件中定义 props:

export default {
  props: {
    message: String
  },
  setup(props) {
    console.log(props.message);
  }
};

在父组件中,我们就可以这样使用并传递数据:

<template>
  <ChildComponent message="Hello from parent" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
</script>

这样,子组件的 Setup 函数就能接收到来自父组件传递的 message 数据。需要注意的是,props 是响应式的,当父组件传递的数据发生变化时,子组件中相应的 props 也会跟着改变。

接下来是 context 参数。context 提供了一些上下文信息,它是一个普通对象,包含了 attrs、slots 和 emit 等属性。

attrs 包含了所有传递给组件但未被识别为 props 的特性。例如:

export default {
  setup(props, context) {
    console.log(context.attrs);
  }
};

slots 则用于访问组件的插槽内容。如果组件有默认插槽或具名插槽,通过 context.slots 就能获取到插槽内容并进行渲染。

而 emit 是用来触发自定义事件的。在子组件中,如果需要向父组件发送事件通知,就可以使用 context.emit。比如:

export default {
  setup(props, context) {
    const handleClick = () => {
      context.emit('customEvent', 'Some data');
    };
    return {
      handleClick
    };
  }
};

在父组件中,就可以监听这个自定义事件:

<template>
  <ChildComponent @customEvent="handleCustomEvent" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
const handleCustomEvent = (data) => {
  console.log(data);
};
</script>

通过合理运用 props 和 context 参数,我们能在 Vue3 的 Setup 函数中更高效地实现组件间的数据传递和交互,让代码结构更加清晰和易于维护。

TAGS: Vue3_Setup函数 Props参数 Context参数 Vue3使用技巧

欢迎使用万千站长工具!

Welcome to www.zzTool.com