1. 程式人生 > >微信小程式製作元件

微信小程式製作元件

微信小程式的元件有兩種方式

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

元件的index.wxml

<view>
  <text>我是元件</text>
<text>傳入元件的值: {{text}}</text>
<text>元件內部的值{{data}}</text>
<text wx:if={{show}}>呼叫了方法</text>
</view>

元件的index.js

Component({
    properties: {
        // 這裡定義了元件對外的屬性,屬性值可以在元件使用時指定
        text:{
           type:String,
           value:''
         }
    },
    data: {
        // 這裡是一些元件內部資料
        data: '我是元件',
         show:false
    },
    methods: {
        // 這裡是一個自定義方法
        show: function(){
          this.setData({show:true})
        }
    }
})

元件的index.json

{
  "component": true
}

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

頁面的index.wxml

<view>
  <text>下面是元件</text>
  <child text='我是父元件傳的值' id='child'></child> 
  <button bindtap='clickBtn'>按鈕</button>
<view>

頁面的index.js

Page({
  onReady: function () {
    //獲得子元件
    this.child = this.selectComponent("#child");
  },
  clickBtn:function(){
    this.child.show();
  }
})

頁面的index.json

{
  "usingComponents": {
    "child": "../child/index"
  }
}

這就完成了一個元件.

第二種方式:

元件的index.wxml

<template name='child'>
  <view>
    <text>我是元件</text>
    <text>我是從父元件傳的值:{{text}}</text>
    <text>我是元件本身的值{{data}}</text>
    <text wx:if='{{show}}'>呼叫了元件的方法</text>
  </view>
</template>

元件的index.js

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

import {child} from './child/index'
APP({child,
   ...
})

如果給元件寫了wxss檔案,要在app.wxss裡引入,如下:

app.wxss

@import './child/index.wxss'

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

<import src='../child/index.wxml'/>
<template is='child'></template>
<button bindtap='clickBtn'>按鈕</button>

當前頁面的js檔案:

let app=getApp();
Page({
  data:{
    data:'父元件傳給子元件的值' 
  },
  onLoad:function(){
    new app.child();
  },
  clickBtn:function(){
    this.show(this.data.data);
  }
})
上面app.js和app.wxss是全域性引用,如果想區域性引用,也可以把全域性的引入寫到區域性去。