微信小程序之組件開發

關於組件得官方文檔描述,請參考自定義組件,本篇僅簡述一下開發中得注意點。

我的組件包目錄是和pages同級的,這個看個人。

1.組件的聲明

需要在share.json裏將component設置爲true

{
  "component": true,
  "usingComponents": {}
}

2.組件的引用

假如想在index裏引用share組件,則需要在index.json裏配置usingComponents,例:

{
  "usingComponents": {
    "component-share": "/component/share/share"
  },

然後在頁面內引用該組件:

<component-share bindintoout="changesharemsg" share-msg="{{shareMsg}}"></component-share>

3.貼一下share的代碼

// component/share/share.js
var util=require('../../utils/util.js')
Component({
  /**
   * 組件的對外屬性,是屬性名到屬性設置的映射表
   * 組件內部 遵循駝峯規則 引用頁面外部使用"-"連接
   */
  properties: {
    shareMsg:String
  },
  lifetimes: {
    attached: function () {
      // 在組件實例進入頁面節點樹時執行
      console.log('在組件實例進入頁面節點樹時執行')
    },
    detached: function () {
      // 在組件實例被從頁面節點樹移除時執行
    },
  },
  observers: {
    'shareMsg': function (newVal) {
      console.log('節點數據發生變化時執行:' + newVal)
    }
  },
  pageLifetimes: {
    show: function () {
      // 引用頁面被展示
      console.log('引用頁面被展示')
    },
    hide: function () {
      // 引用頁面被隱藏
      console.log('引用頁面被隱藏')
    },
    resize: function (size) {
      // 引用頁面尺寸變化
      console.log('引用頁面尺寸變化')
    }
  },
  /**
   * 組件的內部數據,和 properties 一同用於組件的模板渲染
   */
  data: {
    innerData:"內部數據,外部不可更改"
  },

  /**
   * 組件的方法列表
   */
  methods: {
    //更改外部數據
    toOut:function(){
      var that=this
      var msg = util.formatTime(new Date())
      var option={
        "msg": msg
      }
      that.triggerEvent('intoout', option)
    }

  }
})

 

<!--component/share/share.wxml-->
<view>{{shareMsg}}</view>
<view>{{innerData}}</view>
<button bindtap="toOut">點擊我更改外部數據</button>

 

4.貼一下index代碼

//index.js
var util=require('../../utils/util.js')
//獲取應用實例
const app = getApp()

Page({
  data: {
    shareMsg:"外部數據,通過properties內定義的屬性傳遞"
  },
  onLoad: function () {
    var that=this
    that.setData({
      shareMsg: util.formatTime(new Date())
    })
  },
  changesharemsg: function (e, option){
    console.log(e)
    var that = this
    that.setData({
      shareMsg: e.detail.msg
    })
  }
})
<!--index.wxml-->
<!-- 組件內部 遵循駝峯規則 引用頁面外部使用"-"連接 -->
<component-share bindintoout="changesharemsg" share-msg="{{shareMsg}}"></component-share>

 相關的參數的描述,代碼中已註釋。

5.說明一下,demo做了什麼

5.1 首先,組建內shareMsg是沒有初始值的。

在index頁面onLoad內,給shareMsg賦予了一個初始值,通過

share-msg="{{shareMsg}}

 傳遞給組件內的shareMsg屬性

5.2 點擊button按鈕,觸發組件內的toOut事件,通過triggerEvent傳遞給綁定的index頁面的事件changesharemsg,option爲傳遞的參數

that.triggerEvent('intoout', option)

更改了index裏的shareMsg值,然後又傳遞給了組件,重新渲染頁面。

6.僅供參考

項目地址:wechat-component

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章