商城系統(tǒng) 注冊

小程序自定義組件開發(fā),小程序如何自定義開發(fā)

2020-09-27|HiShop
導(dǎo)讀:微信小程序的組件有兩種方式,那么小程序如何制作組件,自定義組件開發(fā),下面為大家介紹。...

  小程序自定義組件開發(fā),小程序如何自定義開發(fā)

  微信小程序的組件有兩種方式,那么小程序如何制作組件,自定義組件開發(fā),下面為大家介紹。

  第一種方式,下面是一個(gè)組件的基本組成部分,樣式表就不寫了,

  組件的index.wxml

  [html] view plain copy

  我是組件

  傳入組件的值: {{text}}

  組件內(nèi)部的值{{data}}

  調(diào)用了方法

  組件的index.js

  [javascript] view plain copy

  Component({

  properties: {

  // 這里定義了組件對外的屬性,屬性值可以在組件使用時(shí)指定

小程序自定義組件開發(fā),小程序如何自定義開發(fā)

  text:{

  type:String,

  value:''

  }

  },

  data: {

  // 這里是一些組件內(nèi)部數(shù)據(jù)

  data: '我是組件',

  show:false

  },

  methods: {

  // 這里是一個(gè)自定義方法

  show: function(){

  this.setData({show:true})

  }

  }

  })

  組件的index.json

  [javascript] view plain copy

  {

  "component": true

  }

  組件寫好了,下面是引入寫好的組件

  頁面的index.wxml

  [html] view plain copy

  下面是組件

  按鈕

  頁面的index.js

  [javascript] view plain copy

  Page({

  onReady: function () {

  //獲得子組件

  this.child = this.selectComponent("#child");

  },

  clickBtn:function(){

  this.child.show();

  }

  })

  頁面的index.json

  [javascript] view plain copy

  {

  "usingComponents": {

  "child": "../child/index"

  }

  }

  這就完成了一個(gè)組件.

  第二種方式:

  組件的index.wxml

  [html] view plain copy

  我是組件

  我是從父組件傳的值:{{text}}

  我是組件本身的值{{data}}

  調(diào)用了組件的方法

  組件的index.js

  [javascript] view plain copy

  let data={

  text:'',

  data:'我是組件本身的值',

  show:false

  }

  let childPanel={

  show:function (text) {

  let _this=this;

  this.setData({

  show:true,

  text:text

  })

  }

  }

  function child() {

  let pages=getCurrentPages();

  let currentPage=pages[pages.length-1];

  this.__page=currentPage;

  Object.assign(currentPage,childPanel);

  currentPage.childPanel=this;

  currentPage.setData(data);

  return this;

  }

  module.exports={

  child

  }

  然后在app.js里引入上面的js文件,如下:

  app.js

  [javascript] view plain copy

  import {child} from './child/index'

  APP({child,

  ...

  })

  如果給組件寫了wxss文件,要在app.wxss里引入,如下:

  app.wxss

  [css] view plain copy

  @import './child/index.wxss'

  在需要引入該組件的頁面,如下:

  [html] view plain copy

  按鈕

  當(dāng)前頁面的js文件:

  [html] view plain copy

  let app=getApp();

  Page({

  data:{

  data:'父組件傳給子組件的值'

  },

  onLoad:function(){

  new app.child();

  },

  clickBtn:function(){

  this.show(this.data.data);

  }

  })

  上面app.js和app.wxss是全局引用,如果想局部引用,也可以把全局的引入寫到局部去。

HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。

更多小程序開發(fā)案例,盡在:http://descansotropical.com/xiaocx/kaifa.html 

電話咨詢 預(yù)約演示 0元開店