微信小程序 component組件的使用 以及 傳值


1、創建component組件

 

 

2、component.js 中的說明

Component({
  /**
   * 組件的屬性列表(對外屬性),屬性設置中可包含三個字段,type 表示屬性類型、 value 表示屬性初始值、 observer 表示屬性值被更改時的響應函數
   */
  properties: {

  },
  /**
   * 組件的初始數據(內部數據),和 properties 一同用於組件的模版渲染
   */
  data: {

  },
  /**
   * 組件的方法列表,包括事件響應函數和任意的自定義方法
   */
  methods: {

  },

  created: function () {
    // 組件生命周期函數,在組件實例進入頁面節點樹時執行,注意此時不能調用setData(節點樹還未導入, 無法使用setData)
    console.log('Component-1 >> created');
  },
  attached: function () {
    // 組件生命周期函數,在組件實例進入頁面節點樹時執行。可以使用setData來初始化數據,但無法操作節點
    console.log('Component-1 >> attached');
  },
  ready: function () {
    // 在組件布局完成后執行,可以獲取到節點信息也可以操作節點
    console.log('Component-1 >> ready');
  },
  moved: function () {
    // 在組件實例被移動到節點樹另一個位置時執行
    console.log('Component-1 >> moved');
  },
  detached: function () {
    // 在組件實例被從頁面節點樹移除時執行
    console.log('Component-1 >> detached');
  },
  lifetimes: {
    // 組件生命周期聲明對象,將組件的生命周期收歸到該字段進行聲明,
    //原有聲明方式仍舊有效,如同時存在兩種聲明方式,則lifetimes字段內聲明方式優先級最高
    created: function () {
      console.log('Component-1 lifetimes >> created');
    },
    attached: function () {
      console.log('Component-1 lifetimes >> attached');
    },
    ready: function () {
      console.log('Component-1 lifetimes >> ready');
    },
    moved: function () {
      console.log('Component-1 lifetimes >> moved');
    },
    detached: function () {
      console.log('Component-1 lifetimes >> detached');
    }
  },
  pageLifetimes: {
    // 組件所在頁面的生命周期聲明對象,目前僅支持頁面的show和hide兩個生命周期
    show: function () {
      console.log('Component-1 pageLifetimes >> Show');
    },
    hide: function () {
      console.log('Component-1 pageLifetimes >> Hide');
    }
  }
})

 

3、頁面中引入組件,在需要引入組件的頁面json文件中引入組件

"usingComponents": {
    "popup":"../components/popup/popup"
  },

 

4、頁面  --傳值-->  組件

      給 頁面wxml中的 "組件標簽" 添加 鍵值對 , 鍵為 : 傳過去的數據 名稱 , 值為 : 傳過去的數據

<popup fromFather="'我是來自頁面的數據'"></popup>

      在組件 js中的 properties方法中 添加 對象 , 對象名為 : 父頁面傳來的數據名稱 , 對象type為 : 數據 的 數據類型

properties: {
    fromFather: {
      type: String,
      value: ""
    },
  },

     組件的 wxml 中,之間展示數據名即可

<text>{{fromFather}}</text>

 

5、組件  --傳值-->  頁面

     子組件 在事件中 , 使用 this.triggerEvent ( '參數一' , { 參數二 } ) 傳值給頁面.
     參數一為 : 傳過去的方法 名稱 , 參數二為 : 傳過去的數據 ( 以鍵值對的形式 )

<button bindtap="editSonData">點擊傳數據給頁面</button>
methods: {
    editSonData(){
      this.triggerEvent ( 'fromSon' , {name:'路西德'} )
    }
  },

      在 父頁面wxml中的 "組件標簽" 添加 bind事件 ( bind + 子組件傳來的方法名稱="方法名" ) ,

<popup bind:fromSon="editData"></popup>

      再在 js 文件中 添加事件的方法 , e . detail 能獲取到 子組件傳來的數據

 

editData(e){
    console.log(e.detail.name)//路西德
  },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM