vue3中的props和emit

发布于:2024-07-16 ⋅ 阅读:(157) ⋅ 点赞:(0)

首先我们要明确props和emit是在父子组件(嵌套组件)中使用的 。

想要在父组件中渲染出子组件里的内容,需要在父组件中导入子组件,并在模板中渲染子组件。

那父子组件中如何通信呢?就需要使用到props和emit。

props

当子组件要接受父组件传递的数据信息时,也可以说是父组件传递数据给子组件时(子组件要显示父组件中的内容),需要使用props传递。

在子组件中,需要声明它所接受的props

<script setup>

const props = defineProps({
msg:string

}) 

</script>   

<template>
{{msg}}
</template>
在父组件中,导入子组件

<script setup>
import {ref} from 'vue'
import children from './children.vue'

导入之后,定义需要传输的数据
const hello=ref( 'hello,my friend')

</script>

<template>

在模板中的子组件内部动态绑定传输的数据

  <children :msg='hello' />

</template>

在子组件中,结果会显示父组件中的hello里的内容,hello的内容变化时,显示的内容会同步变化。

emit

子组件要向父组件触发事件时,也就是说,父组件要显示子组件中的内容时,需要使用emit传递。

在子组件中
<script setup>

//需要声明触发的事件
const emit = defineEmits(['response'])

//emit() 的第一个参数是事件的名称。其他所有参数都将传递给事件监听器。
emit('response', 'hello child')

</script>

在父组件中,需要使用v-on 监听子组件触发的事件
<script setup>

import { ref } from 'vue'
import Child from './Child.vue'

const childMsg = ref('No msg ')
</script>

<template>
//response是子组件中定义的需要触发的事件名称,把子组件中msg的值赋给负组件中的childmsg
  <Child   @response="(msg) => childMsg = msg"  />
  <p>{{ childMsg }}</p>
</template>

在父组件中,结果显示为子组件中的emit传递的第二个参数的值,当值发生变化时,视图也会同步变化。


网站公告

今日签到

点亮在社区的每一天
去签到