vue 父传子 子传父
时间: 2023-11-12 08:59:36 浏览: 44
Vue中父组件向子组件传递数据可以通过props属性实现,子组件向父组件传递数据可以通过$emit方法实现。
具体来说,父组件通过在子组件标签上绑定属性的方式向子组件传递数据,例如:
```html
<template>
<div>
<child-component :prop-name="parentData"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
data() {
return {
parentData: 'Hello from parent component'
}
}
}
</script>
```
在子组件中,可以通过props属性接收父组件传递的数据,例如:
```html
<template>
<div>{{ propName }}</div>
</template>
<script>
export default {
props: {
propName: String
}
}
</script>
```
子组件向父组件传递数据可以通过$emit方法实现,例如:
```html
<template>
<div>
<button @click="sendDataToParent">Send Data to Parent</button>
</div>
</template>
<script>
export default {
methods: {
sendDataToParent() {
this.$emit('event-name', 'Data from child component')
}
}
}
</script>
```
在父组件中,可以通过在子组件标签上绑定事件的方式接收子组件传递的数据,例如:
```html
<template>
<div>
<child-component @event-name="handleDataFromChild"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
handleDataFromChild(data) {
console.log(data) // 'Data from child component'
}
}
}
</script>
```
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)