当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解微信小程序中组件通讯

详解微信小程序中组件通讯

2018年11月05日  | 移动技术网IT编程  | 我要评论

这篇主要讲组件通讯

(1)父组件向子组件传值:

<header title='{{title}}' bind:fn='fn' id='header'></header>

通过title='{{title}}'传向子组件向子组件传递参数

子组件接收参数:

component({
 properties: {
  title: {    // 属性名 type: number, // 类型(必填)
   type: string,//目前接受的类型包括:string, number, boolean, object, array, null(表示任意类型)
  },
  fn: {   
   type: function,
  },
 },
 data: {
    
 },
 methods: {
  // 子组件调用父组件方法
  childfn() {
   console.log(this.data.title)
   this.triggerevent("fn");
   //triggerevent函数接受三个值:事件名称、数据、选项值 
  }
 }
})

methods使用title时 this.data.title 直接就可以获取到

通过 bind:fn='fn'传向子组件向子组件传递方法

方法同样也要在properties接收,methods里定义一个新方法, this.triggerevent("fn") 接收父组件传递过来的方法

(2)父组件调用子组件数据及方法:

首先在父组件js onready 生命周期中获取到组件

onready: function () {
  //获得popup组件
  this.header= this.selectcomponent("#header");
},

比如要调用子组件的一个function方法

// 调用子组件方法
 fn(){
  this.header.fn() //子组件的方法
 },

调用子组件数据的话直接 this.header.msg 就可以拿到子组件的数据

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网