当前位置: 首页 > article >正文

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>




http://www.kler.cn/news/317294.html

相关文章:

  • 多旋翼无人机维修、组装、调试技术详解
  • typora使用和激活
  • 【机器学习】生成对抗网络(GAN)——生成新数据的神经网络
  • 共建智能座舱AI应用生态 夸克合作斑马智行开拓AI搜索新场景
  • 【Linux】SSH:远程连接
  • python 项目中使用Elasticsearch
  • Qt Creator项目模板介绍
  • 使用OVPN导致电脑网速变慢的原因
  • MySQL record 08 part
  • 成功使用DDNS动态域名访问我的群晖NAS(TP-link路由器)
  • Yocto - 使用Yocto开发嵌入式Linux系统_03 基于Poky制作第一个系统
  • vue.js 展示一个树形结构的数据视图,并禁用其中默认选中的节点
  • java并发之并发理论
  • 【自动驾驶】基于车辆几何模型的横向控制算法 | Pure Pursuit 纯跟踪算法详解与编程实现
  • 同一网络下两台电脑IP一样吗?探究局域网内的IP分配机制
  • 释放TK49N65W5 MOSFET的潜力
  • 镭射限高防外破预警装置-线路防外破可视化监控,安全尽在掌握中
  • C++继承(上)
  • 数据结构 - 概述及其术语
  • AI教你学Python 第18天 : 线性数据结构
  • 【LeetCode:1014. 最佳观光组合 + 思维题】
  • 【linux】基础IO(上)
  • 使用 PHPstudy 建立ThinkPHP8 本地集成环境
  • SM2协同签名算法中随机数K的随机性对算法安全的影响
  • (八)使用Postman工具调用WebAPI
  • 花园管理系统
  • 论文阅读与分析:Few-Shot Graph Learning for Molecular Property Prediction
  • 服务器操作系统【sar 命令】
  • MongoDB的备份和恢复命令
  • macos macport软件包管理工具 sudo port install xxx 安装的软件的路径 与 brew install xxx 软件安装路径总结