vue3父子组件通信

一,父传子------defineProps

方法:

在父组件的模板中使用子组件标签,并且给标签自定义属性和属性名,即通过v-bind绑定数值,而后传给子组件;子组件则通过defineProps接收使用。

父组件:

复制代码
<template>
  <div >
	<div>我是父组件</div>
    <<SonCom :fatherProp="msg" ></SonCom> -
  </div>
</template>
<script setup lang='ts'>
  import SonCom from '@/components/SonCom.vue';  // 引入子组件
  import { ref } from 'vue';
  const msg = ref<string>('coderkey')
</script>

子组件:

复制代码
<template>
  <div >
	<div>我是子组件</div>
  </div>
</template>
<script setup lang='ts'>
 import { defineProps } from 'vue';
  let prop = defineProps({
    fatherProp: {
        required: true,
        type: String,
        default: 'pink',
    }
  }) 
  console.log(prop.fatherProp)  // coderkey
</script>

二,子传父------defineEmits

方法:

复制代码
defineEmits['自定义事件名']

子组件中通过emit调用父组件中的自定义事件,给父组件的这个方法里传入数据数据。

父组件:

复制代码
<template>
  <div >
	<div>我是父组件</div>
    <<SonCom :fatherProp="msg" @update:fatherProp="fatherClick"></SonCom> -
  </div>
</template>
<script setup lang='ts'>
  import SonCom from '@/components/SonCom.vue';  // 引入子组件
  import { ref } from 'vue';
  const msg= ref<string>('coderkey')
  
  const fatherClick = (data:any) => {
  console.log(data);  // 子组件传递数据给父组件
}
</script>

子组件:

复制代码
<template>
  <div >
	<div>我是子组件</div>
	<button  @click="sendDateHandle">子传父数据</button>
  </div>
</template>
<script setup lang='ts'>
 import { defineProps,defineEmits } from 'vue';
  let prop = defineProps({
    fatherProp: {
        required: true,
        type: String,
        default: 'pink',
    }
  }) 
  console.log(prop.msg)  // coderkey
  
  let emit = defineEmits(['update:fatherProp'])
  const sendDateHandle = () => {
  	emit('update:fatherProp','子组件传递数据给父组件')
  }
</script>

相关推荐
其实防守也摸鱼1 小时前
Day 3 · Agent Loop:从调用模型到控制循环 —— 课件精讲笔记
服务器·开发语言·javascript·数据库·人工智能·笔记·ecmascript
夕水1 小时前
我把颜色选择器拆成了 15 个插件,最后长成了 22 个包
前端·javascript·typescript
大今野1 小时前
2026 专转本计算机|移动互联网关键技术:SOA、Web2.0 与 HTML5 考点全解(附例题)
前端·html·html5·专转本
JudithHuang2 小时前
Vue3 与后端联调:代理、Mock 与接口约定
前端·vue
Swot2 小时前
工具转换 vs LLM 转换:以 Markdown 转 AsciiDoc 为例
前端
uuware2 小时前
Lupine.js 的 Native 5 端实现:一套代码覆盖 iOS、Android、macOS、Windows 和 Web
前端·typescript
用户88956195481712 小时前
戴上眼镜就把今天听完:绿光快报的 AIUI 语音新闻智能体
javascript
lisw052 小时前
前端:概念、历史、内容、挑战与展望!
前端
stormsha2 小时前
ResizeObserver loop completed with undelivered notifications:它只是个警告,但也是你代码的供词
javascript·css