vue子组件向父组件传值
时间: 2023-08-19 07:04:32 浏览: 44
在Vue中,子组件向父组件传递值可以通过自定义事件来实现。以下是一个示例:
首先,在子组件中定义一个方法,用于触发自定义事件并传递值:
```vue
<template>
<button @click="sendData">传递值给父组件</button>
</template>
<script>
export default {
methods: {
sendData() {
this.$emit('custom-event', 'Hello from child component');
}
}
}
</script>
```
在父组件中,通过监听子组件触发的自定义事件,接收传递的值:
```vue
<template>
<div>
<child-component @custom-event="receiveData"></child-component>
<p>接收到的值:{{ receivedData }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
receivedData: ''
}
},
methods: {
receiveData(data) {
this.receivedData = data;
}
}
}
</script>
```
在父组件中,通过监听子组件触发的自定义事件`@custom-event`,调用`receiveData`方法来接收传递的值,并将其存储在`receivedData`数据中。然后在模板中通过插值表达式`{{ receivedData }}`来显示接收到的值。
当子组件中的按钮被点击时,会触发自定义事件`custom-event`,并传递字符串`'Hello from child component'`给父组件。父组件接收到该值后更新`receivedData`,并在模板中显示出来。
这样就实现了子组件向父组件传递值的功能。
相关推荐
![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)
![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)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)