vue3组件通信, 父传子和子传父

vue3组件通信

场景一. 父传子

<script setup>
 import sonCom from "./components/SonCom.vue";
</script>

<template>
 <div class="fatherBody">
   <h1>父组件</h1>
   <sonCom message="父组件传递给子组件的内容" />
 </div>
</template>

<style scoped>
.fatherBody {
 width: 400px;
 height: 400px;
 border:1px solid #000;
}
</style>

​ 子组件用宏函数defineProps接收父组件传递过来的值

<script setup>
   defineProps({
       message: String
   })
</script>

<template>
   <div class="sonBody">
       <h1>子组件</h1>
       <div>{{ message }}</div>
   </div>
</template>

<style scoped>
.sonBody {
   margin: auto;
   width: 200px;
   height: 200px;
   color: #f00;
   border: 1px solid #f00;
}
</style>

如果要在js脚本使用父组件传递过来的值, 只需定义一下, 其它不变

<script setup>
   const props = defineProps({
       message: String
   })
   console.log(props.message)
</script>

<template>
   <div class="sonBody">
       <h1>子组件</h1>
       <div>{{ message }}</div>
   </div>
</template>

若果父组件需要传递响应式的数据

<script setup>
 import { ref } from 'vue'
 import SonCom from "./components/SonCom.vue";
 // 传递响应式数据
 const count = ref(100)
 setTimeout(() => {
   count.value = 300
 }, 3000)
</script>

<template>
 <div class="fatherBody">
   <h1>父组件</h1>
   <SonCom :count="count" message="父组件传递给子组件的内容" />
 </div>
</template>
<script setup>
   const props = defineProps({
       message: String,
       count: Number
   })
   console.log(props.message)
</script>

<template>
   <div class="sonBody">
       <h1>子组件</h1>
       <div>{{ message }} <br>父组件传递的响应式数据{{ count }}</div>
   </div>
</template>

场景二. 子传父

<script setup>
 import { ref } from 'vue'
 import SonCom from "./components/SonCom.vue";
 const sonMsg = ref('')
 const getMessage = (msg) => {
   sonMsg.value = msg
 }
</script>

<template>
 <div class="fatherBody">
   <h1>父组件</h1>
   <h2>子组件传递过来的值: {{ sonMsg }}</h2>
   <SonCom @get-message="getMessage" />
 </div>
</template>

<style scoped>
.fatherBody {
 width: 400px;
 height: 400px;
 border:1px solid #000;
}
</style>

子组件通过编译器宏函数defineEmits传递数据

<script setup>
   const emit = defineEmits(['get-message'])
   const sonMsg = () => {
     emit('get-message', 'this is son message')
   }
</script>

<template>
   <div class="sonBody">
       <h1>子组件</h1>
       <button @click="sonMsg">点击按钮传值给父组件</button>
   </div>
</template>

<style scoped>
.sonBody {
   margin: auto;
   width: 200px;
   height: 200px;
   color: #f00;
   border: 1px solid #f00;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值