WeChat applet pass parameters

what is an event


Events are the communication method from the view layer to the logic layer. Events can feed back the user's behavior to the logic layer for processing. 
Events can be bound to components, and when the trigger event is reached, the corresponding event handler function in the logic layer will be executed. 
Event objects can carry additional information such as id, dataset, touches.

write picture description here

write picture description here

Looking at the picture, because there is a lot of data to be passed, we carry parameter information through dataset . If there is only one parameter, it can be passed by id .

Detailed explanation (take common tap clicks as an example)

wxml

<view id="tapTest" data-hi="WeChat" bindtap="tapName"> Click me! </view>
  • 1

JS

Page({
  tapName: function(event) {
    console.log(event)
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5

event print result

{
"type":"tap",
"timeStamp":895,
/////////////////////////////////
"target": {
  "id": "tapTest",
  "dataset":  {
    "hi":"WeChat"
  }
},
"currentTarget":  {
  "id": "tapTest",
  "dataset": {
    "hi":"WeChat"
  }
},
///////////////////////////////
"detail": {
  "x":53,
  "y":14
},
"touches":[{
  "identifier":0,
  "pageX":53,
  "pageY":14,
  "clientX":53,
  "clientY":14
}],
"changedTouches":[{
  "identifier":0,
  "pageX":53,
  "pageY":14,
  "clientX":53,
  "clientY":14
}]
}

Note two points:

1. The data - name  cannot have capital letters. If necessary, you can use - (underscore) to connect words. When compiling, the applet will automatically capitalize the first letter of the second word. The code in the picture is for its own logo, so the first letter of the second word is capitalized, but it is not necessary. Objects cannot be stored in data-* attributes.

2. Pay attention to the difference between target and currentTarget in the print result .

target The source component that triggered the event. 
The current component to which the currentTarget event is bound.

If you bind an event on the parent container and pass parameters, when you click on the parent container, the component to which the event is bound and the source component that triggers the event are the same element, so both currentTarget and target can get parameters, but when you When the child element is clicked, the target is not the component bound by the event, so the parameters cannot be obtained. 
Due to the mechanism of event bubbling, events bound to the parent container can still be triggered, so currentTarget can still get parameters.

illustrate

idPassing parameters datasetis similar, except that the last time to get the value is different.event.currentTarget.id


点击打开原链接

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326056164&siteId=291194637