父子组件之间的通信

App.vue是项目的一个入口
这里写图片描述
引入之后,要注册才能使用。
这里写图片描述

父向子组件传参:
父组件直接定义属性(msg)和属性值(something interesting)-子组件想要取得父组件中定义的属性值(something interesting)-在子组件中定义props,属性名(msg)在数组中-子组件即可得到该参数(this.msg)。

子向父组件传参:
在componentA.js中

<button v-on:click='onClickMe'>open mouse</button>

子组件中给按钮绑定一个click事件,执行onClickMe函数,

onClickMe:function(){
      this.$emit('listen-from-child',this.msg);
      console.log(this.msg);
    }

在onClickMe函数中触发自定义的listen-from-child事件,在父组件中app.vue文件中

<componentA msgfromfather='you die' v-on:listen-from-child='listenChild'></componentA>

componentA中绑定了listen-from-child事件,click之后触发到该事件,又执行app.vue中的listenChild函数,

listenChild:function(msg){
      this.childSay=msg;
    }

让this.childSay的值为子组件中传入的this.msg。想要在页面中显示this.childSay的值,还要在app.vue中的data中声明childSay属性。

<p>childsay:{{childSay}}</p>
data:function(){
    return {
      title: '<span>?</span>qmm to do a list',
      items:Store.fetch(),
      liClass:'thisisliclass',
      newItem:'',
      childSay:''//在这儿声明
    }
  }

这样在父组件里就能接收到子组件中传的参啦。
dispatch, broadcast在vue2.0中已经被弃用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,父子组件之间通信可以通过props和emit来实现。 1. 使用props:父组件可以通过props属性向子组件传递数据。在子组件中,可以通过接收props属性来使用这些数据。在父组件中,可以通过修改props属性的值来实现与子组件通信。 父组件示例: ```vue <template> <div> <child-component :message="parentMessage"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: 'Hello from parent component' }; } }; </script> ``` 子组件示例: ```vue <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { props: { message: { type: String, required: true } } }; </script> ``` 2. 使用emit:子组件可以通过emit方法触发自定义事件,然后父组件可以通过监听这些事件来获取子组件传递的数据。 父组件示例: ```vue <template> <div> <child-component @child-event="handleChildEvent"></child-component> <p>{{ messageFromChild }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { messageFromChild: '' }; }, methods: { handleChildEvent(message) { this.messageFromChild = message; } } }; </script> ``` 子组件示例: ```vue <template> <div> <button @click="sendMessageToParent">Send Message to Parent</button> </div> </template> <script> export default { methods: { sendMessageToParent() { this.$emit('child-event', 'Hello from child component'); } } }; </script> ``` 这两种方式都可以实现父子组件之间通信,你可以根据具体的需求选择使用哪种方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值