vue3组合式api,子组件如何像父组件传值
时间: 2023-08-12 22:15:32 浏览: 180
在Vue3中,子组件可以通过props接收父组件传递的值,也可以通过$emit方法向父组件发送事件。具体操作如下:
1. 父组件传递值给子组件:
父组件中使用子组件时,可以在子组件标签上使用属性绑定的方式,将父组件中的数据传递给子组件:
```html
<template>
<div>
<ChildComponent :msg="parentMsg" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: { ChildComponent },
data() {
return {
parentMsg: 'Hello from parent!'
}
}
}
</script>
```
子组件中通过props接收父组件传递的值:
```html
<template>
<div>
{{ msg }}
</div>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
msg: String
}
}
</script>
```
2. 子组件向父组件发送事件:
子组件中通过$emit方法触发一个自定义事件,父组件通过在子组件标签上使用v-on绑定自定义事件的方式,监听子组件触发的事件并处理:
```html
<template>
<div>
<button @click="sendMsg">发送消息到父组件</button>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
methods: {
sendMsg() {
this.$emit('send-msg', 'Hello from child!')
}
}
}
</script>
```
父组件中监听子组件触发的事件,并处理:
```html
<template>
<div>
<ChildComponent @send-msg="handleMsg" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: { ChildComponent },
methods: {
handleMsg(msg) {
console.log(msg)
}
}
}
</script>
```
阅读全文
相关推荐

















