自定义组件向页面传递数据、样式和事件

1.向自定义组件传递数据

首先在自定义组件的js文件中定义要传递的属性

Component({
  /**
   * 组件的属性列表
   * title为要传递的数据定义字段
   */
  properties: {

    title:{
       type:String,
       value:'默认的标题',
       observer:function(newVal,Oldval){
         console.log(newVal);
         console.log(Oldval);
       }
    },
  },

})

组件的内容如下,标题中没有写死,而是{{title}}

{{title}}
我是内容

在其他页面使用,首先在其他页面的json文件中注册

{
  "usingComponents": {
     "myprop":"/components/myprop/myprop"
  }
}

在其他页面使用时通过title向自定义组件传递数据




2.向自定义的组件传递样式

首先在自定义组件的 js 文件中定义样式传递使用的字段

Component({
  //titleclass为定义的名称
  externalClasses:['titleclass'],
})

然后在自定义的组件页面中写好

{{title}}
我是内容

最后在其他页面中使用时




red / green / blue分别为在使用的页面的wxss页面中定义的样式

3.自定义组件传递事件

首先需要在自定义组件中将事件发出,比如点击按钮后

//以下为自定义组件中的button

然后在btnclick方法中将事件发出,发出的事件名为increment

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

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

  },

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

    btnclick(){
      //第一个参数为发出的事件名,第二个参数是传递的数据,按对象传递,第三个参数是设置选项
      this.triggerEvent('increment',{name:'xiaoming',sex:1},{})
    }

  }
})

最后,在其他页面使用时监听发出的事件



在方法handleIncrement方法中处理自定义事件发出来的事件和传递过来的数据

 handleIncrement(event){
    this.setData({
      counter:this.data.counter+1
    })
    //event中有自定义组件传递过来的数据
    console.log(event);
  },

4.直接调用组件修改数据或直接调用组件内的方法

有一个组件名字叫 Iamcomponent,在某个页面中使用如下

要修改组件内的数据或调用组件中的方法,首先通过class或id得到组件对象,
然后再修改数据或调用方法

    handleIncrement(event){
    //修改my-sel中的counter数据
    //1.通过class或id得到组件对象
    // const Iamcomponent = this.selectComponent(".sel-class");
    const Iamcomponent = this.selectComponent("#sel-id");


    //2.调用setData修改数据(不是很合理)
    // Iamcomponent .setData({
    //   counter:Iamcomponent.data.counter+20
    // })

    //3.调用组件中的方法修改数据
    Iamcomponent.incrementCounter(10);
  }

你可能感兴趣的:(自定义组件向页面传递数据、样式和事件)