Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

WeChat Mini Program Component Development: Structure, Lifecycle, and Communication

Tech 1

Component Definition

A component in a WeChat Mini Program is a reusable and independent UI unit, defined using the Component constructor. Its structure primarily includes properties, data, and methods.

  • properties: Defines the component's external interface, allowing data to be passed in from a parent component.
  • data: Defines the component's internal state.
  • methods: Contains the component's custom functions.

The following example illustrates a basic counter component:

Component({
  properties: {
    componentTitle: {
      type: String,
      value: 'Default Title'
    }
  },
  data: {
    internalCounter: 0
  },
  methods: {
    incrementCounter() {
      this.setData({
        internalCounter: this.data.internalCounter + 1
      });
      this.triggerEvent('counterchange', { value: this.data.internalCounter });
    }
  }
});

In this code, componentTitle is a property with a default value. The incrementCounter method updates the internal state internalCounter and emits a custom event named counterchange to notify the parent component.

Component Lifecycle

Components have a lifecycle managed by specific callback functions. The primary lifecycle callbacks are:

  • created: Triggered when the component instance is created. Properties and data are not yet available.
  • attached: Triggered when the component is attached to the page's node tree. Properties and data are initialized.
  • ready: Triggered after the component's layout is rendered and ready for interaction.
  • moved: Triggered if the component is moved within the node tree.
  • detached: Triggered when the component is removed from the node tree.
Component({
  created() {
    console.log('Component instance created.');
  },
  attached() {
    console.log('Component attached to page node tree.');
  },
  ready() {
    console.log('Component rendering complete.');
  },
  moved() {
    console.log('Component moved to another node.');
  },
  detached() {
    console.log('Component removed from node tree.');
  }
});

Additionally, components can react to the lifecycle of the page they reside in using the pageLifetimes definition.

Component({
  pageLifetimes: {
    show() {
      // Executes when the page is shown or becomes active.
    },
    hide() {
      // Executes when the page is hidden or backgrounded.
    },
    resize(size) {
      // Executes when the page window size changes.
    }
  }
});

Component Communication

Communication between components is essential for building interactive applications. The primary methods are event passing and shared data.

Event Passing

Child components can communicate with parent components by triggering custom events. The parent component listens for these events.

Child Component (triggering the event):

// child-component.js
Component({
  methods: {
    sendDataToParent() {
      this.triggerEvent('customevent', { message: 'Data from child' });
    }
  }
});

Parent Component (listening for the event):

<!-- parent-component.wxml -->
<child-component bind:customevent="onChildEvent" />
// parent-component.js
Component({
  methods: {
    onChildEvent(event) {
      console.log('Received data:', event.detail.message); // Outputs: 'Data from child'
    }
  }
});

Shared Data via App Instence

For global state management across different pages and components, data can be stored in the global App instance.

Defining Global Data in app.js:

// app.js
App({
  globalData: {
    userToken: null,
    appSettings: {}
  }
});

Accessing Global Data in a Component:

// any-component.js
const appInstance = getApp();
Component({
  attached() {
    const token = appInstance.globalData.userToken;
    console.log('Current token:', token);
  }
});

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.