Vue组件间传值

一、父传子

子组件中定义一个props,用来取出父组件传来的值

<script>
    export default {
        props:['msg'] //子组件定义props
    }
</script>

父组件中对子组件的自定义属性绑定父组件的变量

<template>
  <div class="parent">
    //子组件,绑定data中需要传送的值
    <Children :msg="message"></Children>
  </div>
</template>
 
<script>
import Children from '../components/Children'
 
export default {
  name: 'Parent',
  components: {
      Children
  },
  data() {
      return {
          message:'hello world'
}
},
}
</script>
 二、子传父

使用自定义事件,在父组件中给子组件绑定一个处理函数

<template>
  <div class="parent">
    <Children @numChange = 'getNewNum'></Children>
  </div>
</template>
 
<script>
import Children from '../components/Children'
 
export default {
  data(){
      return {numFromSon:0}
  },
  methods:{
     getNewNum(val){
         this.countFromSon = val
     } 
  }
</script>

子组件中使用$emit出发父组件中的函数进行传参

export default {
  data(){
      return {num 0}
  },
  methods:{
     count(){
       this.count +=1
       this.$emit('numChange',this.count)
      }
   }
}
三、兄弟组件间传值

采用事件总线eventBus,可以理解为在组件之间建立一个中转站

1.创建一个新的eventBus实例

import Vue from 'vue'
 
const eventBus = new Vue() //创建Vue实例:eventBus
 
exoprt default eventBus //暴露

2.在各组件中引入eventBus

import eventBus form '../eventBus.js'

3.使用$emit传参

eventBus.$emit('sendMsg','Hello World')

4.使用$on接受参数

eventBus.$on('sendMeg',(msg)=>{
     console.log(msg)
  }
)

总结:多练

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值