vue中父传子
时间: 2023-06-21 11:22:51 浏览: 40
在Vue中,父组件向子组件传递数据有多种方法,以下是其中的两种常见方法:
1.使用props属性
在父组件中,可以通过props属性来传递数据给子组件,例如:
```
<template>
<div>
<child-component :message="msg"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
data() {
return {
msg: 'Hello World!'
}
}
}
</script>
```
在子组件中,需要在props选项中声明接收的属性,例如:
```
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
```
这样,父组件中的msg数据就会被传递到子组件中的message属性中,子组件就可以使用这个数据了。
2.使用$emit方法
在父组件中,可以通过$emit方法来向子组件发送事件,并传递数据,例如:
```
<template>
<div>
<button @click="sendMessage">发送消息</button>
<child-component @receive-msg="handleReceive"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
sendMessage() {
this.$emit('send-msg', 'Hello World!')
},
handleReceive(msg) {
console.log(msg)
}
}
}
</script>
```
在子组件中,需要监听父组件发送的事件,并在事件处理函数中接收数据,例如:
```
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
mounted() {
this.$emit('receive-msg', 'Hello Vue!')
},
props: {
message: String
},
methods: {
handleMessage(msg) {
this.message = msg
}
},
mounted() {
this.$on('send-msg', this.handleMessage)
},
beforeDestroy() {
this.$off('send-msg', this.handleMessage)
}
}
</script>
```
这样,父组件中的sendMessage方法就会触发一个send-msg事件,并传递数据到子组件中,子组件中监听该事件,并在handleMessage方法中接收数据并更新message属性,最终展示在页面上。
相关推荐
![](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)