vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue3父子组件通信、兄弟组件实时通信

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

作者:acheding

这篇文章主要介绍了vue3父子组件通信、兄弟组件实时通信方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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>

效果:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文