Small program custom components

Why components? Separate complex pages into multiple components, with clear structure, simple maintenance and reusability

1. Define components

a. New directory components All components of the project will be placed in this directory

b. Right-click on components to create a new directory w-tab-control

c. Creating new components by right-clicking on w-tab-control automatically generates four files (js, json, wxml, wxss)

//  1.w-tab-control.wxml
<view class="titleclass">I am the title.</view>  //titleclass is a class passed over using component pages
<view class="tab-control">
  <block wx:for="{{titles}}" wx:key="{{index}}">
    <view class="w-tab-item {{currentIndex == index ? 'active' :'' }}" 
bind:tap="tabClick" data-index="{{index}}">
      <text >{{item}}</text>
    </view>
  </block>
</view>
<my-cpn />  //Other components referenced



//  2.w-tab-control.js
Component({
  properties: {
    titles:{      //Data passed over using component pages
      type:Array,  //Indicating type
      value:[]    //Default value
    }
  },
  externalClasses: ['titleclass'], //Receive the class passed over using the page
  data: {
    currentIndex:0
  },
  methods: {
    tabClick:function(e){
    
      var index = e.currentTarget.dataset.index;
      this.setData({
        currentIndex: index
      })

      // Pass events to pages that use components  
      this.triggerEvent("tabOnClick", 
                { index, name: this.properties.titles[index]},
                {}
            )
    },
  }
})

//  3.w-tab-control.json
{
  "component": true,  //Components cannot be deleted when they are used
  "usingComponents": {
         "my-cpn":"/components/my-cpn/my-cpn",
    }  //You can refer to other components in it.
}



//  4.w-tab-control.wxss
.tab-control{
  line-height: 44px;
  display: flex;
}
.w-tab-item{
  flex: 1;
  text-align: center;
}
.active text{
  color:red;
  border-bottom:3px solid red;
  padding:10px 5px;
}

2. Reference components need to refer to components in / pages/cpn/cpn

// 1. cpn.json

{
  "usingComponents": {
    "my-cpn":"/components/my-cpn/my-cpn",
    "w-tab-control":"/components/w-tab-control/w-tab-control" //Reference component
  }
}

// 2.cpn.wxml  
//Page usage
// titles item component delivers data and receives it in component js
// Bid: tabOnClick= "tabclick" returns events  
    //Bind: tabOnClick tabOnClick is the name returned
    // Name of tabclick current page (cpn.js) event

<w-tab-control 
    titles="{{['home page','details','introduce']}}" 
    titleclass="red"
    bind:tabOnClick="tabclick" />


// 3.cpn.js

Page({

  tabclick:function(e){  //Events passed by components
    console.log(e)
  }

})

//  4.cpn.wxss

.red{
    color:red
}

Note: Component names consist of (a-z, -,) and cannot be used with special symbols and capital letters

Tags: JSON

Posted on Sun, 06 Oct 2019 03:32:16 -0700 by plex303