2025年vue2父子组件传值props(vue父子组件如何传递参数)

vue2父子组件传值props(vue父子组件如何传递参数)Vue 中 父子 组件 之间传递信息可以通过 pro ps 和 emit 事件来实现 父组件 向子组件 传递信息 在父组件 中 通过 pro ps 将数据传递给子组件 子组件 通过 pro ps 接收数据即可 父组件 lt template gt lt div gt lt child component message amp

大家好,我是讯享网,很高兴认识大家。

Vue父子组件之间传递信息可以通过props和$emit事件来实现

  1. 组件向子组件传递信息:

在父组件通过props将数据传递给子组件,子组件通过props接收数据即可。

组件


讯享网

&lt;template&gt; &lt;div&gt; &lt;child-component :message=&quot;message&quot;&gt;&lt;/child-component&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import ChildComponent from &#39;https://blog.csdn.net/weixin_/article/details/ChildComponent.<em>vue</em>&#39; export default { components: { ChildComponent }, data() { return { message: &#39;Hello, child component!&#39; } } } &lt;/script&gt; 

讯享网

组件

讯享网&lt;template&gt; &lt;div&gt; {{ message }} &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { <em>pro</em><em>ps</em>: { message: String } } &lt;/script&gt; 
  1. 组件向父组件传递信息:

在子组件通过$emit事件触发父组件的方法,将需要传递的数据作为参数传递即可。

组件

&lt;template&gt; &lt;div&gt; &lt;button @click=&quot;sendMessage&quot;&gt;Send message to parent&lt;/button&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { methods: { sendMessage() { this.$emit(&#39;send-message&#39;, &#39;Hello, parent component!&#39;) } } } &lt;/script&gt; 

组件

讯享网&lt;template&gt; &lt;div&gt; &lt;child-component @send-message=&quot;receiveMessage&quot;&gt;&lt;/child-component&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import ChildComponent from &#39;https://blog.csdn.net/weixin_/article/details/ChildComponent.<em>vue</em>&#39; export default { components: { ChildComponent }, methods: { receiveMessage(message) { console.log(message) } } } &lt;/script&gt; 

在子组件通过$emit触发了send-message事件,父组件通过@send-message监听到事件,并且将传递的数据作为参数传递给了receiveMessage方法。

小讯
上一篇 2025-05-09 15:20
下一篇 2025-05-13 17:17

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/158749.html