Often, we will encounter structures that are used on multiple pages during development, and consider encapsulating these structures as common components that can be referenced on different pages.

1. Create the Components folder and corresponding components

  • Create a Components folder
  • Creating a Component Directory
  • In the component directory, right-click -> Select Component, type a file name such as index (no suffix required), and press Enter to quickly generate.js,. Json,. WXML, and. WXSS related files

2. Write code in relevant files

For example, if you have a video list page where the video item is used across multiple pages, consider extracting the logical authoring of the video item into a common component:

2-1. Extract the relevant item code

At this point, in index. WXML in video-item-v1

<wxs src=".. /.. /utils/format.wxs" module="format"></wxs> <view class="item"> <view class="album"> <image class="image" src="{{item.cover}}" mode="widthFix"></image> <view class="info"> <view class="count">{{format.formatCount(item.playCount)}}</view> <view class="duration">{{format.formatDuration(item.mv.videos[0].duration)}}</view> </view> </view> <view class="content"> {{item.name}} - {{item.artistName}} </view> </view>Copy the code
  • The required item comes from the parent component

2-2. Define the properties required by the component

We can see that each child component needs the item traversed by the parent component, so in the js of the child component, we need to define the attributes and types to be received in its properties:

  properties: {
    item: {
      type: Object,
      value: {}
    }
  }
Copy the code

2-3. The parent component uses encapsulated child components

Configure the child components you want to use in the parent component JSON file

  • Use “usingComponents” to configure the child components you want to use
  • Key represents the name of the child component
  • Value indicates the location of the child component

2-3-2. Reference the child component in the parent component and pass what the child component needs

<view class="video">
  <view class="item" wx:for="{{topMVs}}" wx:key="id">
    <video-item item="{{item}}"></video-item>
  </view>
</view>
Copy the code

At this point, the extraction of the child components is complete