Vue +父组件调用子组件方法 + 子组件回调父组件方法

0. 整体代码:

 【父组件】:

<template>
    <div>
      <span style="color: red">-------------------------------------------</span><br>
      <span style="color: red">这是父组件页面</span>&emsp;
      <button @click="clickParentMethod">点击</button>
      <SubComponent ref="SubComponent" @callParentMethod="callParentMethod" trans-data="传递的参数"/>
    </div>
</template>

<script>
import SubComponent from "@/components/SubComponent";

export default {
  name: "SideOne",
  components: { SubComponent },
  methods: {
    clickParentMethod () {
      console.log('clickParentMethod')
      this.$refs.SubComponent.callSubMethod()
    },
    callParentMethod (val) {
      console.log('callParentMethod: ' + val)
    }
  }
}
</script>

 【子组件】:

<template>
  <div>
    <span>-------------------------------------------</span><br>
    <span>这是子组件页面</span>&emsp;
    <button @click="clickSubMethod">点击</button>
  </div>
</template>

<script>
export default {
  name: "SubComponent",
  props: {
    transData: {
      type: String
    }
  },
  methods: {
    clickSubMethod() {
      console.log('clickSubMethod')
      this.$emit('callParentMethod','回调的参数')
    },
    callSubMethod() {
      console.log('callSubMethod: ' + this.transData)
    }
  }
}
</script>
1. 要点:
<SubComponent ref="SubComponent" @callParentMethod="callParentMethod" trans-data="传递的参数"/>

【整体效果】:
在这里插入图片描述

 1.1. 父组件调用子组件方法:
  • 子组件标签添加ref属性,值为子组件,如ref=“SubComponent”
  • 父组件this.$refs.SubComponent.callSubMethod()调用子组件方法
 1.2. 子组件回调父组件方法:
  • 子组件标签绑定回调方法,如@callParentMethod=“callParentMethod”
  • 子组件 this.$emit(‘callParentMethod’,‘回调的参数’)回调父组件方法
  • 子路由回调父路由同样适用,在< router-view > 标签内绑定回调方法即可
 1.3. 父组件传递参数给子组件:
  • 子组件标签绑定参数变量和传递的值,如trans-data=“传递的参数”,也可以使用:transData='param’形式,param要在data中定义
  • 子组件使用props来接收
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值