当我们使用Vue时,组件通信是构建复杂应用不可或缺的一部分。Vue 3.2引入了<script setup>语法糖,使得编写组件更加简洁和直观。在这篇博客中,我们将深入讨论Vue 3.2中的组件通信技术,并提供一些具体的代码示例。

1. Props

Props是Vue中最基本的组件通信方式之一,它允许父组件向子组件传递数据。在<script setup>中,你可以直接使用defineProps来声明和接收props。

<template>
  <div>{{ message }}</div>
</template>

<script setup>
const props = defineProps(['message']);
</script>

在这个例子中,父组件可以通过传递一个名为message的prop来向子组件传递数据。

2. Emit

子组件可以通过$emit方法向父组件发送消息。在<script setup>中,你可以使用defineEmits声明要触发的事件。

<template>
  <button @click="sendMessage">Send Message</button>
</template>

<script setup>
const { emit } = defineEmits(['messageSent']);

const sendMessage = () => {
  emit('messageSent', 'Hello from child!');
};
</script>

在这里,当按钮被点击时,messageSent事件将会被触发,并且父组件可以监听这个事件。

3. Provide / Inject

provideinject是一种高级的组件通信方式,它允许祖先组件向所有后代组件传递数据。在<script setup>中,你可以使用defineExposewithDefaults来提供和注入数据。

<script setup>
import { ref, defineExpose, withDefaults } from 'vue';

const sharedData = ref('Shared Data');

const expose = defineExpose({
  sharedData,
});

export default withDefaults({
  expose,
});
</script>

在这里,祖先组件通过provide提供sharedData,然后子孙组件通过inject来接收它。

4. Refs

Refs可以用于在组件之间传递可变的数据。在<script setup>中,你可以使用ref来创建一个可响应的引用。

<template>
  <div>{{ sharedCount.value }}</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const sharedCount = ref(0);

onMounted(() => {
  sharedCount.value = 10;
});
</script>

在这个例子中,sharedCount是一个在组件之间共享的可变引用。

5. Provide / Inject(高级用法)

provideinject还可以用于提供和注入响应式数据。在<script setup>中,你可以使用reactivereadonly来实现这一点。

<script setup>
import { reactive, readonly, defineExpose, withDefaults } from 'vue';

const sharedState = reactive({
  count: 0,
});

const expose = defineExpose({
  sharedState: readonly(sharedState),
});

export default withDefaults({
  expose,
});
</script>

在这里,sharedState是一个响应式对象,祖先组件通过provide提供它,然后子孙组件通过inject来接收它的只读版本。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue