An overview of the

I encapsulated a relatively simple wechat popover widget, mainly to teach you the use and understanding of wechat widget, because wechat small program to introduce components is very little, so I will share my understanding with you.

A preface

I believe you in the development of small programs will encounter a function of multiple use, such as the pop-up box. At this time, we first think of componentized development, is to package the pop-up box into a component, and then where to use where to call, right, it seems that we are thinking of people, but how to achieve it. Maybe you will read the official document, but the official document of wechat is not very clear, so it is very painful to write. Today, we will develop wechat components together, sit firmly, the old driver to drive.

Ii. Concrete Implementation

Let’s first implement a simple popover component, as shown below:



1. Create a component folder to store our components, which store the components we use. What we are going to do today is popup a box, create a folder popup to store our component templates, right-click and choose new component, it will automatically generate component templates WXSS, WXML, json and js, as shown in the figure

2. We can write some component styles and layouts, which are similar to the page style. I won’t go into details, but post the code directly:

popup.wxml

<view class="wx-popup" hidden="{{flag}}">
  <view class='popup-container'>
    <view class="wx-popup-title">{{title}}</view>
    <view class="wx-popup-con">{{content}}</view>
    <view class="wx-popup-btn">
      <text class="btn-no" bindtap='_error'>{{btn_no}}</text>
      <text class="btn-ok" bindtap='_success'>{{btn_ok}}</text>
    </view>
  </view>
</view>Copy the code

popup.wxss

/* component/popup.wxss */
.wx-popup {
  position: absolute;
  left: 0;
  top: 0;

  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 5); }.popup-container {
  position: absolute;
  left: 50%;
  top: 50%;

  width: 80%;
  max-width: 600rpx;
  border: 2rpx solid #ccc;
  border-radius: 10rpx;
  box-sizing: bordre-box;
  transform: translate(50%, 50%);overflow: hidden;
  background: #fff;
}

.wx-popup-title {
  width: 100%;
  padding: 20rpx;
  text-align: center;
  font-size: 40rpx;
  border-bottom: 2rpx solid red;
}

.wx-popup-con {
  margin: 60rpx 10rpx;
  text-align: center;
}

.wx-popup-btn {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.wx-popup-btn text {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30%;
  height: 88rpx;
  border: 2rpx solid #ccc;
  border-radius: 88rpx;
}
Copy the code

The style and the layout and the layout is already written and the next thing I want to talk about is

Component constructor

The Component constructor can be used to define components, specifying their properties, data, methods, and so on when called.

Definition section type If required describe
properties Object Map no The external properties of a component are a mapping table of property names to property Settings, which can contain three fields,typeRepresents the property type,valueRepresents the initial value of the attribute,observerRepresents the response function when the property value is changed
data Object no Component internal data, andpropertiesTogether with template rendering of components
methods Object no Component methods, including event response functions and arbitrary custom methods, for use of event response functions, seeComponent events
behaviors String Array no For code reuse mechanisms between components similar to mixins and traits, seebehaviors
created Function no The component lifecycle function, executed when the component instance enters the page node tree, cannot be called at this timesetData
attached Function no Component lifecycle function, executed when the component instance enters the page node tree
ready Function no Component lifecycle functions that are executed after the component layout is complete, at which point node information can be retrieved (usingSelectorQuery )
moved Function no Component lifecycle function, executed when the component instance is moved to another location in the node tree
detached Function no Component lifecycle function, executed when the component instance is removed from the page node tree
relations Object no For the definition of relationships between components, seeIntercomponent relationship
externalClasses String Array no The external style classes accepted by the component, seeExternal style classes
options Object Map no See other sections of the documentation for some component options

Tips:

  • ComponentThe components constructed by the constructor can also be used as pages.
  • usethis.dataYou can get internal data and attribute values, but do not modify them directlysetDataModification.
  • Lifecycle functions cannot pass through component methodsthisAccess to.
  • Attribute names should not start with data, that is, do not namedataXyzBecause in WXML,data-xyz=""Is treated as a node dataset, not a component property.
  • During the definition and use of a component, the component’s property name and data field cannot conflict with each other (even though they are in different definition sections).

Component is the key JS

popup.js:

Component({
  options: {
    multipleSlots: true // Enable multiple slot support in the options at component definition
  },
  /** * Component property list */
  properties: {
    title: {            / / the property name
      type: String.// Type (mandatory), currently accepted types include: String, Number, Boolean, Object, Array, null (for any type)
      value: 'title'     // The initial value of the property (optional), if not specified one will be selected based on the type
    },
    // Popover content
    content: {
      type: String.value: 'content'
    },
    // Popup cancel button text
    btn_no: {
      type: String.value: 'cancel'
    },
    // Popup confirm button text
    btn_ok: {
      type: String.value: 'sure'}},/** * The initial data of the component */
  data: {
    flag: true,},/** * list of component methods */
  methods: {
    // Hide the cartridge
    hidePopup: function () {
      this.setData({
        flag:!this.data.flag
      })
    },
    // Display the popbox
    showPopup () {
      this.setData({
        flag:!this.data.flag
      })
    },
    /* * Internal private methods suggest starting with an underscore * triggerEvent is used to trigger events */
    _error () {
      // Cancels the callback
      this.triggerEvent("error")
    },
    _success () {
      // Trigger a successful callback
      this.triggerEvent("success"); }}})Copy the code

We’ll use a triggerEvent here:

When a custom component fires an event, you need to use the triggerEvent method, specifying the event name, detail object, and event options.

Options for triggering events include:

Option of type If required The default value describe
bubbles Boolean no false Whether the event bubbles
composed Boolean no false Whether events can cross component boundaries. If false, events can only be raised in the node tree of the reference component, not in any other component
capturePhase Boolean no false Whether the event has a capture phase

Now that a popover component is wrapped, it’s time to call.

UsingComponents = usingComponents = usingComponents = usingComponents = usingComponents = usingComponents

index.json

{
  "usingComponents": {
    "popup": "/component/popup/popup"}}Copy the code

Now you’re almost done and all you need to do is quote it on the front page.

<! --index.wxml-->
<view class="container">
  <view class="userinfo">
    <button bindtap="showPopup">Am I</button>
  </view>
  <popup id='popup' 
      title='component' 
      content='Did you get it?' 
      btn_no='没有' 
      btn_ok='Learned'
      bind:error="_error"  
      bind:success="_success">
  </popup>
</view>Copy the code

Configure index.js plus click events

//index.js
// Get the application instance
const app = getApp()

Page({
  onReady: function () {
    // Get the POPUP component
    this.popup = this.selectComponent("#popup");
  },

  showPopup() {
    this.popup.showPopup();
  },

  // Cancel the event
  _error() {
    console.log('You hit Cancel');
    this.popup.hidePopup();
  },
  // Confirm the event
  _success() {
    console.log('You hit OK');
    this.popup.hidePopup(); }})Copy the code

A popover component is complete. Look at the effect:

If you think the article is good and helpful to you, please share it with your friends and give a thumbs-up. If you don’t know anything, you can leave a comment below.
If you want to see the source code, you can go to my Github download, welcome to star, github: github.com/Mr-MengBo/M…