组件传值

一、父组件向子组件传值

1.子组件定义props值

  // 要想修改props的值 可以把props的值转存到data
  //props:['init'],
  props: {
    //自定义属性A:{/* 配置选项 */}
    init: {
      //如果外界使用count组件的时候没有传递init属性 则默认值生效
      default: 0,
      // init的值类型必须是Number数字
      type: Number,
      //必填
      required: true
    }
  }

2.父组件引入子组件

  <!-- 9加冒号就不是字符串 v-bind 如果9前面不加:默认把9当成一个字符串-->
  <MyCount :init=9></MyCount>

2.子组件向父组件传值

1.在子组件通过$emit触发自定义事件

  //修改数据时 通过$emit()触发自定义事件
  this.$emit('numChange',this.count)

2.父组件使用子组件传来的值

  <!-- 子传父 Right是子组件-->
  <Right @numChange="getNewCount"></Right>
  data() {
      return{
      //定义接受子组件传递过来的数据
      countFromRight: 0
    }
  },
  methods: {
    getNewCount(val) {
      this.countFromRight = val
    }
  }

3.兄弟组件传值

  1. 利用总线bus传值 导出一个Vue实例

    import Vue from 'vue'
    
    export default new Vue()
    
  2. 发送方

    //1.导入eventBus.js
    import bus from '../eventBus.js'
    
    //2.通过eventBus发送数据
    bus.$emit('share', this.str)
    
  3. 接收方

    //1.导入eventBus.js
    import bus from '../eventBus'
    
    //2.为bus绑定自定义事件
    bus.$on('share',(val)=>{
     this.msgFromLeft = val
    })
    
posted @ 2024-05-30 14:52  _你听得到  阅读(12)  评论(0)    收藏  举报