小程序-兄弟传值

使用到this.triggerEvent(’ ',{},{}),第一个参数是自定义事件名称,这个名称是在页面调用组件时bind的名称,第二个对象就是想要的状态和值

1、创建公共组件child,child2,父组件index

在父组件中index.wxml

<child1 bind:parentReceive="parentCallBack"></child1>
<child2 name="{{ name }}" type="{{ type }}"></child2>

index.js 

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
   
    name: '成都',
    type: 1
  },
  
  
  // 第三步:在回调函数的事件对象中进行数据更新
  parentCallBack(event) {
    console.log(event)
    let  name  = event.detail.name;
    this.setData({ // 更新数据
      name: name,
      type: 2
    })
  }
  
})

在child1.js中

// component/child/child1.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    onMusic() {
      /*
       第一步:兄弟组件music,通过自定义事件的方式通知父组件
      */
      this.triggerEvent('parentReceive', {name: "终于等到你"}, {type:1})
    }
  }
})

child1.wxml中

<button bind:tap="onMusic">music组件通知它的兄弟组件Movie更新数据</button>

child2.wxml中

<view>歌曲名称:{{ name }}</view>
<view>类型:{{ type }}</view>

child2.js中

   * 组件的属性列表
   */
  properties: {
    name: String,
    type: Number
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {

  }
})
发布了107 篇原创文章 · 获赞 23 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_42092177/article/details/104591496