vue3 如何父子组件传值
时间: 2023-10-19 08:20:52 浏览: 35
Vue3 中父子组件传值可以通过 props 和 emit 实现。
1. 通过 props 传递数据
在父组件中传递数据,可以将数据绑定到子组件的 props 上。在子组件中,可以通过 props 接收并使用这些数据。
父组件:
```html
<template>
<ChildComponent :message="parentMessage"/>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent component'
}
}
}
</script>
```
子组件:
```html
<template>
<div>{{message}}</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
```
2. 通过 emit 传递事件
在子组件中触发事件,父组件可以通过监听子组件的事件来获取数据。
子组件:
```html
<template>
<button @click="handleClick">Click me</button>
</template>
<script>
export default {
methods: {
handleClick() {
this.$emit('child-click', 'Hello from child component');
}
}
}
</script>
```
父组件:
```html
<template>
<ChildComponent @child-click="handleChildClick"/>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildClick(message) {
console.log(message);
}
}
}
</script>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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_column_c1.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)