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>

相关推荐
attitude.x3 分钟前
PyTorch 动态图的灵活性与实用技巧
前端·人工智能·深度学习
β添砖java7 分钟前
CSS3核心技术
前端·css·css3
空山新雨(大队长)20 分钟前
HTML第八课:HTML4和HTML5的区别
前端·html·html5
猫头虎-前端技术1 小时前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
阿珊和她的猫1 小时前
探索 CSS 过渡:打造流畅网页交互体验
前端·css
元亓亓亓1 小时前
JavaWeb--day1--HTML&CSS
前端·css·html
β添砖java1 小时前
CSS的文本样式
前端·css
前端小趴菜051 小时前
css - 滤镜
前端·css
祈祷苍天赐我java之术1 小时前
理解 CSS 浮动技术
前端·css