vue3 父子组件通信

1.props

父组件传参不变,子组件接收:

通过defineProps 来接受, 无需额外引入,直接使用

复制代码

<template>
<div class="menu">
  菜单区域 {{ title }}
  <div>{{ data }}</div>
</div>
</template>

<script setup lang="ts">
defineProps<{
  title:string,
  data:number[]
}>()
</script>

复制代码

 withDefaults是个函数也是无须引入开箱即用接受一个props函数第二个参数是一个对象设置默认值

type Props = {
    title?: string,
    data?: number[]
}
withDefaults(defineProps<Props>(), {
    title: "张三",
    data: () => [1, 2, 3]
})

 

2.emit

父组件接收不变,子组件传参如下:

在子组件绑定了一个click 事件 然后通过defineEmits 注册了一个自定义事件

点击click 触发 emit 去调用我们注册的事件 然后传递参数

const emit = defineEmits(['increment'])
const count = ref(100)
const increment = () => {
  count.value++
  emit('increment', count.value)
}

 

defineExpose

明确哪些数据或方法应该被暴露给父组件 

复制代码
<template>
  <Child ref="childComponentRef" />
  <button @click="getChildData">获取子组件数据</button>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import Child from './Child.vue';

// 定义一个 ref 来存储子组件的实例
const childComponentRef = ref<InstanceType<typeof Child> | null>(null);

function getChildData() {
  if (childComponentRef.value) {
    console.log(childComponentRef.value.list);
  }
}
</script>
复制代码

 

const list = reactive<number[]>([4, 5, 6])
 
defineExpose({
    list
})

 

posted on   sss大辉  阅读(598)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示