在
Vue 中,
父子 组件 之间可以通过props和$emit来
实现 数据的共享。
1. 使用props
传递数据:
父 组件可以通过props属性将
数据 传递给子
组件。在子
组件 中,可以通过props选项接收
父 组件 传递的
数据,并在子
组件 中使用。
vue//父 组件<template><div><child-component :message="message"></child-component></div></template><script>import ChildComponent from 'https://blog.csdn.net/_/article/details/ChildComponent.vue';export default {components: {ChildComponent},data() {return {message: 'Hello from parent component'};}};</script>// 子组件<template><div><p>{{ message }}</p></div></template><script>export default {props: ['message']};</script>
2. 使用$emit触发事件:
子
组件可以通过$emit
方法触发一个自定义事件,并将
数据作为参数
传递给
父 组件。在
父 组件 中,可以通过监听子
组件触发的事件来获取子
组件 传递的
数据。
vue//父 组件<template><div><child-component @message-updated="updateMessage"></child-component><p>{{ message }}</p></div></template><script>import ChildComponent from 'https://blog.csdn.net/_/article/details/ChildComponent.vue';export default {components: {ChildComponent},data() {return {message: ''};},methods: {updateMessage(newMessage) {this.message = newMessage;}}};</script>// 子组件<template><div><button @click="sendMessage">Send Message</button></div></template><script>export default {methods: {sendMessage() {this.$emit('message-updated', 'Hello from child component');}}};</script>
这样,
父 组件就可以通过props接收子
组件 传递的
数据,子
组件也可以通过$emit触发事件将
数据 传递给
父 组件。
今天的文章 vue父子组件传递数据(vue父子组件传方法)分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/39300.html