vue 组件通信 子向父(学习)

本文介绍了Vue组件间的通信方式,特别是子组件如何向父组件传递信息。通过绑定自定义事件和事件处理函数实现子组件触发父组件的方法。同时,讨论了为何不建议子组件直接修改父组件传入的值,强调了单向数据流的概念,并明确了props中的变量为只读。最后,阐述了组件通信的其他方式,包括父向子的通信。
摘要由CSDN通过智能技术生成

vue 组件通信 子向父(学习)

组件内通信

父 -> 子
子 -> 父

需求

当子想要去改变父里的数据

效果

在这里插入图片描述

在这里插入图片描述

关键代码

  1. 父组件内,绑定自定义事件和事件处理函数语法:@自定义事件名=“父methods里函数名”
<template>
  <div>
    <!-- 目标: 子传父 -->
    <!-- 1. 父组件, @自定义事件名="父methods函数" -->
    <MyProduct v-for="(obj, ind) in list" :key="obj.id"
    :title="obj.proname"
    :price="obj.proprice"
    :intro="obj.info"
    :index="ind"
    @subprice="fn"
    ></MyProduct>
  </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 组件向父组件通信的常用方式有两种:使用事件和使用props。 1. 使用事件:组件可以通过触发一个自定义事件来向父组件传递消息。在组件中使用`$emit`函数触发事件,并传递需要传递的数据。在父组件中使用`v-on`指令监听组件触发的事件,并在对应的方法中处理接收到的数据。 示例代码如下: 组件: ```vue <template> <button @click="sendMessage">发送消息</button> </template> <script> export default { methods: { sendMessage() { this.$emit('message', 'Hello from child component!'); } } } </script> ``` 父组件: ```vue <template> <div> <child-component @message="handleMessage"></child-component> <p>{{ receivedMessage }}</p> </div> </template> <script> export default { data() { return { receivedMessage: '' } }, methods: { handleMessage(message) { this.receivedMessage = message; } } } </script> ``` 2. 使用props:父组件可以通过将数据传递给组件的props来实现与组件的通信。在父组件中通过属性绑定将数据传递给组件,在组件中使用props来接收父组件传递的数据。 示例代码如下: 父组件: ```vue <template> <div> <child-component :message="parentMessage"></child-component> </div> </template> <script> export default { data() { return { parentMessage: 'Hello from parent component!' } } } </script> ``` 组件: ```vue <template> <p>{{ message }}</p> </template> <script> export default { props: ['message'] } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

259-aaa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值