vue3父子组件通信、兄弟组件实时通信

目录

1.父组件向子组件通信

2.子组件向父组件通信

3.兄弟组件实时通信 


1.父组件向子组件通信

父组件:Father

<script setup>
import OneSon from "./oneSon.vue";
import { reactive } from "vue";

const state = reactive({
  fatherData: "I am from Father.",
});
</script>

<template>
  <p>I am Father.</p>
  <OneSon :fatherDataName="state.fatherData"></OneSon>
</template>

<style scoped></style>

子组件:OneSon

<script setup>
import { defineProps } from "vue";

defineProps({
  fatherDataName: String,
});
</script>

<template>
  <p>I am OneSon.</p>
  <p>{{ fatherDataName }}</p>
</template>

<style scoped></style>

效果:

2.子组件向父组件通信

子组件:OneSon

<script setup>
import { reactive, defineEmits } from "vue";

const state = reactive({
  sonData: "I am from Son.",
});
const emit = defineEmits(["sonDataName"]);
const emitSonData = () => {
  emit("sonDataName", state.sonData);
};
</script>

<template>
  <p @click="emitSonData">I am OneSon.</p>
</template>

<style scoped></style>

父组件:Father

<script setup>
import OneSon from "./oneSon.vue";
import { reactive } from "vue";
const state = reactive({
  receive: "",
});
const getSonData = (value) => {
  state.receive = value;
};
</script>

<template>
  <p>I am Father.</p>
  <OneSon @sonDataName="getSonData"></OneSon>
  <p>{{ state.receive }}</p>
</template>

<style scoped></style>

效果:

3.兄弟组件实时通信 

子组件1:OneSon

<script setup>
import { reactive, defineEmits } from "vue";

const state = reactive({
  sonData: true,
});
const emit = defineEmits(["sonDataName"]);
const emitSonData = () => {
  emit("sonDataName", state.sonData);
};
</script>

<template>
  <p @click="emitSonData">I am OneSon.</p>
</template>

<style scoped></style>

子组件2:AnotherSon

<script setup>
import { reactive, defineExpose } from "vue";

const state = reactive({
  display: false,
});
const showAnotherSon = (val) => {
  state.display = val;
};
const hidden= () => {
  state.display = false;
};
defineExpose({ showAnotherSon });
</script>

<template>
  <p v-if="state.display" @click="hidden()">I am AnotherSon.</p>
</template>

<style scoped></style>

父组件:Father

<script setup>
import OneSon from "./oneSon.vue";
import AnotherSon from "./anotherSon.vue";
import { ref } from "vue";

const anotherSon = ref(null);
const getSonData = (val) => {
  anotherSon.value.showAnotherSon(val);
};
</script>

<template>
  <p>I am Father.</p>
  <OneSon @sonDataName="getSonData"></OneSon>
  <AnotherSon ref="anotherSon"></AnotherSon>
</template>

<style scoped></style>

效果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值