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

setup函数子传父普通写法

父组件

<template><div><p>接收的数据: {{ receivedData }}</p><Demo4Chiren2 @custom-event="handleGetWeb" /></div>
</template><script>
import { ref } from 'vue';
import Demo4Chiren2 from './demo4Chiren2.vue';export default {components: { Demo4Chiren2 },setup() {const receivedData = ref(null);const handleGetWeb = (data) => {console.log(data); // 这里打印接收到的数据receivedData.value = data;};return {handleGetWeb, receivedData};}
}
</script>

子组件

记住一定要在setup哪里标上{emit},不然要报错,我搞了半天才晓得。很奇怪的一点,我看别人视频上,就没写{emit}就可以用,但是我为什么要

<template><div><button @click="sendData">发送数据</button></div>
</template><script>
import { defineComponent } from 'vue';export default defineComponent({setup(props, { emit }) {const sendData = () => {const data = { message: 'Hello from Demo4Chiren2' };emit('custom-event', data);};return { sendData };}
});
</script>

vue3中setup函数子传父普通写法,子暴露,以及自己踩过的坑

子组件:一定要return,还有它暴漏的方式还不一样。

<template><div><button @click="sendData">发送数据</button></div>
</template><script>
import { defineComponent, ref } from 'vue';export default defineComponent({setup(props, { emit }) {const sendData = () => {const data = {message: 'Hello from Demo4Chiren2'};emit('custom-event', data);};const exposedData = ref("我是子暴露的数据");const sayHi = () => {return "我是子暴露的方法被调用返回的结果";};return {sendData, exposedData, sayHi};},expose: ['exposedData', 'sayHi']
});
</script>

父组件

<template><div><h1>父组件</h1><Demo4Chiren2 @custom-event="handleCustomEvent" ref="demoChild" /><button @click="callChildMethod">调用子组件方法</button><p>子组件数据: {{ childData }}</p></div>
</template><script>
import { defineComponent, ref } from 'vue';
import Demo4Chiren2 from './Demo4Chiren2.vue'; // 请根据实际路径调整export default defineComponent({components: {Demo4Chiren2},setup() {const demoChild = ref(null);const childData = ref('');const handleCustomEvent = (data) => {console.log('接收到子组件数据:', data);childData.value = data.message;};const callChildMethod = () => {if (demoChild.value) {console.log(demoChild.value.sayHi());}};return {demoChild,childData,handleCustomEvent,callChildMethod};}
});
</script>

http://www.lryc.cn/news/437540.html

相关文章:

  • seafaring靶场漏洞测试攻略
  • 简单示例,搞懂PowerBI的ALL(),ALLEXCEPT()和ALLSELECTED()的区别
  • Collection
  • 19章 泛型
  • 基于python+django+mysql+Nanodet检测模型的水稻虫害检测系统
  • 计算机网络27、28——Linux命令1、2
  • 【Python深度学习】逆强化学习(IRL):通俗揭开学习背后的奥秘
  • Linux:五种IO模型
  • ansible企业实战
  • 面向对象程序设计之模板进阶(C++)
  • 电巢科技携Ecosmos元宇宙产品亮相第25届中国光博会
  • Redis 入门 - 收官
  • Windows技术栈企业基础底座(1)-为基于Windows的Nginx安装证书
  • ThreeJS入门(002):学习思维路径
  • 基于ssm+vue+uniapp的新生报到系统小程序
  • 掌握 JavaScript ES6+:现代编程技巧与模块化实践
  • AttackGen - AI 网络安全事件响应测试工具,附下载链接
  • CAD2020安装方法
  • ubuntu安装mongodb实操学习
  • RabbitMQ 基础入门
  • Unity 特殊文件夹
  • Monster Sound FX Pack 2 怪物恶魔野兽声效包
  • linux常用环境配置
  • SoapShell 更新 | 新增调用cmd执行系统命令
  • Ubuntu查看系统用户信息
  • 入门AI绘画 | 手把手教学Stable Diffusion
  • 基于SpringBoot+Vue+MySQL的热门网络游戏推荐系统
  • SpringBoot + Vue + ElementUI 实现 el-table 分页功能详解
  • 游戏、网关等服务借助Docker容器化并使用Kubernetes部署、更新等
  • Vue面试题4