Vue.js Emit

在学习Vue.js 过程中发现有的例子不全面,记录下这些方便大家参考:

教程 | Vue.js (vuejs.org)

在Vue.js教程中介绍Emit的时候,仅初始化生效,这就导致Parent Component只可以在初始化时使用回调函数才可以获取到Child Component发送的消息。源代码如下:

<!--ChildComp.vue-->
<script setup>
const emit = defineEmits(['response'])

emit('response', 'hello from child')
</script>

<template>
  <h2>Child component</h2>
</template>

<!--App.vue, 即Parent-->
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const childMsg = ref('No child msg yet')
</script>

<template>
  <ChildComp @response="(msg) => childMsg = msg" />
  <p>{{ childMsg }}</p>
</template>

优化后如下:Parent组件可以接收子组件输入框的内容

<!--ChildComp.vue-->

<script setup>
import{ref} from 'vue'
const emit = defineEmits(['response'])

const msg=ref('')
function sendMsg()
{
  emit('response',msg.value)
}
//emit('response',msg.value)//这个是原来的,只可以在加载的时候调用一次,导致@response只可以显示的用"(msg)=>{childMsg=msg;}", 而不可以调用function receiveMsg(msg)。
</script>

<template>
  <h2>Child component</h2>
  <input v-model="msg" placeholder="send message to parent" />
  <button @click="sendMsg">
    Send Msg
  </button>
</template>


<!--App.vue, 即Parent-->
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const childMsg = ref('No child msg yet')
//此处是通过增加一个function发送
function receiveMsg(msg)
{
  childMsg.value=msg;
}

</script>

<template>
  <ChildComp @response="receiveMsg"  />
  <p>Message from Child: {{ childMsg }}</p>
</template>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值