Vue3 孙组件直接传给父组件,写一个例子
时间: 2023-03-25 12:01:00 浏览: 51
可以这样写:
在子组件中,定义一个变量并将其作为参数传递给父组件的方法:
```
<template>
<div>
<button @click="handleClick">点击我</button>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
data() {
return {
message: 'Hello, Vue3!'
}
},
methods: {
handleClick() {
this.$emit('pass-message', this.message)
}
}
}
</script>
```
在父组件中,监听子组件传递的参数并进行处理:
```
<template>
<div>
<child-component @pass-message="handleMessage"></child-component>
<p>子组件传递的消息:{{ message }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
data() {
return {
message: ''
}
},
methods: {
handleMessage(message) {
this.message = message
}
}
}
</script>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)