组件之间传值使用方法

props/$emit

父组件传子组件

子组件

export default {
  name: "Component2",
  props: {
    username: {
      type: String,
      default: ''
    }
  },
}

父组件

<component2 :username="username"></component2>

子组件传父组件

子组件

methods: {
  update() {
    this.$emit('update', '日向雏田')
  }
},

父组件

<component2 @update="update"></component2>
methods: {
  update(item) {
    this.name = item;
  },
}

ref

父组件访问子组件(调用方法)

父组件

<component2 ref="component2"></component2>
mounted() {
  // 使用$refs
  console.log(this.$refs.component2.age);
  // 通过$refs调用子组件方法
  this.$refs.component2.update();
}

$children/$parent

父组件访问子组件

mounted() {
  // 使用$children拿子组件的值
  console.log("子组件的值:", this.$children[0].age);
}

子组件访问父组件

mounted() {
  // 使用$parent拿父组件的值
  console.log("父组件的值:", this.$parent.sex);
}

eventBus

跨组件通信

main.js

export const EventBus = new Vue()

发送方

import {EventBus} from '../../main'
methods: {
  // 通过eventbus发送事件
  event() {
    EventBus.$emit("incremented", this.person)
  }
},

接收方

import {EventBus} from '../../main'
mounted() {
  // 接收EventBus数据
  EventBus.$on('incremented', (re) => {
    this.name = re;
    console.log(re);
  })
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值