自定義組件向頁面?zhèn)鬟f數(shù)據(jù)、樣式和事件

1.向自定義組件傳遞數(shù)據(jù)

首先在自定義組件的js文件中定義要傳遞的屬性

Component({
  /**
   * 組件的屬性列表
   * title為要傳遞的數(shù)據(jù)定義字段
   */
  properties: {

    title:{
       type:String,
       value:'默認(rèn)的標(biāo)題',
       observer:function(newVal,Oldval){
         console.log(newVal);
         console.log(Oldval);
       }
    },
  },

})

組件的內(nèi)容如下,標(biāo)題中沒有寫死,而是{{title}}

<view class='title'>{{title}}</view>
<view class="content">我是內(nèi)容</view>

在其他頁面使用,首先在其他頁面的json文件中注冊

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

在其他頁面使用時通過title向自定義組件傳遞數(shù)據(jù)

<myprop title="哈哈哈哈"/>
<myprop title="嘿嘿" />
<myprop title="呵呵" />

2.向自定義的組件傳遞樣式

首先在自定義組件的 js 文件中定義樣式傳遞使用的字段

Component({
  //titleclass為定義的名稱
  externalClasses:['titleclass'],
})

然后在自定義的組件頁面中寫好

<view class='title titleclass'>{{title}}</view>
<view class="content">我是內(nèi)容</view>

最后在其他頁面中使用時

<myprop title="哈哈哈哈" titleclass="red" />
<myprop title="嘿嘿"  titleclass= "green" />
<myprop title="呵呵" titleclass= "blue"/>

red / green / blue分別為在使用的頁面的wxss頁面中定義的樣式

3.自定義組件傳遞事件

首先需要在自定義組件中將事件發(fā)出,比如點(diǎn)擊按鈕后

//以下為自定義組件中的button
<button size="mini" bindtap="btnclick">+1</button>

然后在btnclick方法中將事件發(fā)出,發(fā)出的事件名為increment

Component({
  /**
   * 組件的屬性列表
   */
  properties: {

  },

  /**
   * 組件的初始數(shù)據(jù)
   */
  data: {

  },

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

    btnclick(){
      //第一個參數(shù)為發(fā)出的事件名,第二個參數(shù)是傳遞的數(shù)據(jù),按對象傳遞,第三個參數(shù)是設(shè)置選項(xiàng)
      this.triggerEvent('increment',{name:'xiaoming',sex:1},{})
    }

  }
})

最后,在其他頁面使用時監(jiān)聽發(fā)出的事件

<myevent bind:increment="handleIncrement"/>

在方法handleIncrement方法中處理自定義事件發(fā)出來的事件和傳遞過來的數(shù)據(jù)

 handleIncrement(event){
    this.setData({
      counter:this.data.counter+1
    })
    //event中有自定義組件傳遞過來的數(shù)據(jù)
    console.log(event);
  },

4.直接調(diào)用組件修改數(shù)據(jù)或直接調(diào)用組件內(nèi)的方法

有一個組件名字叫 Iamcomponent,在某個頁面中使用如下
<Iamcomponent class="sel-class" id="sel-id"></Iamcomponent>

要修改組件內(nèi)的數(shù)據(jù)或調(diào)用組件中的方法,首先通過class或id得到組件對象,
然后再修改數(shù)據(jù)或調(diào)用方法

    handleIncrement(event){
    //修改my-sel中的counter數(shù)據(jù)
    //1.通過class或id得到組件對象
    // const Iamcomponent = this.selectComponent(".sel-class");
    const Iamcomponent = this.selectComponent("#sel-id");


    //2.調(diào)用setData修改數(shù)據(jù)(不是很合理)
    // Iamcomponent .setData({
    //   counter:Iamcomponent.data.counter+20
    // })

    //3.調(diào)用組件中的方法修改數(shù)據(jù)
    Iamcomponent.incrementCounter(10);
  }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容