Use Component to create custom components

WeChat small program through the Component (Object Object) to create custom components, the official document the following Component | WeChat open document

Preface: Why use custom components

When we develop a large application, the reuse of modules can greatly improve the efficiency of code writing, reduce the complexity of code and the difficulty of later maintenance. In wechat small programs, similar page layout modules are often used in different pages, so we can use Component(Object Object) to create custom components. Let’s take a look.

Step 1: Create a Component using Component

Start by creating a Components folder in the root directory to hold all the custom components we will create

Then, under the Components folder, create a folder for the components we want to customize. (Custom components are also composed of json, WXML, WXSS, and JS files, which are similar to pages.)

At this point our custom component is basically created.

Step 2: Declare the components you want to use

When we need to use custom components in our business pages, we need to declare the custom components we want to use. For example, if you want to use the custom component myHeader you just created in the index page, go to the index.json file and modify it as follows:

{
  "usingComponents": {
    "myHeader" : ".. /.. /components/myHeader/myHeader"}}Copy the code

Note: “myHeader” is the name of the custom component you want to use, where the component address uses a relative path.

Step 3: Use custom components in your page

After creation and declaration, we can use the custom components we created in our own business pages. Again, you can use the myHeader tag in the index. WXML file just as you would use the View tag, which is the beauty of custom components.

<! --pages/index/index.wxml-->
<view>pages/index/index.wxml</view>
<myHeader> </myHeader>

Copy the code

The effect is as follows:

Please give me more advice if you have any problems.