prop子传父,setup方式
时间: 2023-10-08 18:10:56 浏览: 26
在 Vue.js 中,可以通过自定义事件(`$emit`)来实现子组件向父组件传递数据。在子组件中,可以通过 `setup` 函数中的 `context` 参数来访问 `$emit` 方法,从而触发自定义事件。以下是一个简单的例子:
```html
<template>
<div>
<child-component @message="handleMessage"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
methods: {
handleMessage(value) {
console.log(value); // 输出:Hello World
},
},
};
</script>
```
在子组件中,可以通过 `$emit` 方法来触发自定义事件:
```html
<template>
<button @click="sendMessage">发送消息</button>
</template>
<script>
import { defineEmits } from 'vue';
export default {
emits: ['message'],
setup(_, context) {
const sendMessage = () => {
context.emit('message', 'Hello World');
};
return {
sendMessage,
};
},
};
</script>
```
注意,在 `setup` 函数中访问 `$emit` 方法时,需要使用 `context.emit`,而不是 `this.$emit`。同时,需要在组件的 `emits` 选项中声明自定义事件的名称,以便在父组件中使用 `@eventName` 的方式监听事件。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)