vue3父子组件传值
时间: 2023-06-22 08:19:40 浏览: 84
在Vue3中,可以使用Props和emit来实现父子组件之间的数据传递。
1. Props
父组件通过props向子组件传递数据,子组件通过props接收数据。
父组件中使用:
```html
<template>
<child-component :propName="parentData"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentData: '父组件数据'
}
}
}
</script>
```
子组件中使用:
```html
<template>
<div>{{ propName }}</div>
</template>
<script>
export default {
props: {
propName: {
type: String,
default: ''
}
}
}
</script>
```
2. emit
子组件通过emit向父组件触发事件,父组件通过v-on监听事件并处理数据。
子组件中使用:
```html
<template>
<button @click="handleClick">点击</button>
</template>
<script>
export default {
methods: {
handleClick() {
this.$emit('eventName', '子组件数据');
}
}
}
</script>
```
父组件中使用:
```html
<template>
<child-component @eventName="handleEvent"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleEvent(data) {
console.log(data); // 子组件数据
}
}
}
</script>
```
以上就是Vue3父子组件传值的两种方式,可以根据具体场景选择使用。
相关推荐
![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_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)