WeChat applet: event parameter passing

In the daily development of WeChat applets, we need events to carry parameters to the functions to be executed in specific scenarios, but because the event parameter passing methods of applets are different, it is not possible to add after the event name after binding the event. Parentheses carry parameters.

Mini-program binding events, the default double quotes are event names, so if we want to implement event parameter passing in the WeChat applet at this time, we can use data-* custom attribute names to pass parameters.

Components can be provided with data-*custom attribute passing parameters, where *represents the name of the parameter

for example: 

The code is as follows (wxml): 

<view>
  <view class="center">{
   
   { num }}</view>
  <button bindtap="add" data-num="{
   
   {5}}">点击加 5 </button>
</view>

It can be seen that the click event add is defined in the code , and the parameter passing is completed through the custom attribute data-num , and the parameter is 5  ; where num is the name of the parameter.

So, how to get the parameters carried by the event?

In the event processing function, event.target.dataset.参数名the value of the specific parameter can be obtained by passing

 The code is as follows (js):

data: {
    num: 0
},
add(e) {
    console.log(e)
    this.setData({
        num: this.data.num + e.target.dataset.num
    })
},

Print the entire event and you can see the parameter 5 carried by the custom attribute data-num .

At this time , the passed parameters  can be used in the method through e.target.dataset.num .

Example:

 The page is a simple data rendering plus a click button, which can trigger an event by clicking the button and carry parameters, and operate the parameters to modify the data, so as to achieve the effect on the picture.

Guess you like

Origin blog.csdn.net/KazariFox/article/details/126345842