The specific implementation of the custom component of the applet + the communication between the page and the custom component

Keywords: JSON

The specific steps are as follows:

1. Create a component

The singer list in the figure is a component, which is usually placed in the objects for specification.

2. Reference components in the json file of the page

//Want to be inindex.wxml The correspondingindex.json To configure this
{
  "usingComponents": {
    "songList":"/components/songList/songList"
  }
}

After reference, it can be used in wxml file

  //index.wxml
  ...
  <songList id='songList'></songlist> 
  ...

Remember the key value of the corresponding component in the json file

3. Methods and properties of using components

A method of fun is defined in the component
//songList.js
Component({
  ...
  methods: {
    fun(v){
      console.log(v)
    }
  }
  ...
})
This can be called in the page
Page({
...
  onready(){
     this.singList = this.selectComponent("#singList");
     this.singList.fun("value");
     //value
  }
  ...
})

4. Page value / method to component

This is how the page is configured
  //index.wxml
  ...
  <songList 
        id='songList' 
        value1='str' 
        value2='{{obj}}'
        bind:action:'exFun'
        //exFun is the name of the method you want to call in the component
        >
  </songlist> 
  ...
//index.js
Page({
  data:{
      obj:{
        a:"one",
        b:"two"
         }
  },
  exFun(v){
      console.log(v) 
  }
})
This is used in components
Component({
  ...
  properties: {
    //The values passed from the configuration page should correspond to the key values one by one
    'value1':{
     type:String, //Required. Currently accepted types include: String, Number, Boolean, Object, Array, null (indicating any type)
     value:""     //Optional, the default value. If the page does not transmit a value, the default value will be used
    },
    'value2':{
     type:Object, //Required. Currently accepted types include: String, Number, Boolean, Object, Array, null (indicating any type)
     value:""     //Optional, the default value. If the page does not transmit the value, the default value will be used
    }

  },
  methods(){
     fun(){
       this.triggerEvent("action");
       //The triggerEvent function accepts three values: event name, data, and option value  
     }
  }
  ...
})
When fun() is called, exFun in index.js will be executed

Posted by brendandonhue on Fri, 01 May 2020 18:32:38 -0700