Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This morning when I was studying the official documents of wechat applets, I accidentally found a funny usage: applets can actually pass functions to their sub-components, and the sub-components call the method of the parent component to obtain values. I think this function is quite practical in complex development. Maybe I am ignorant, but it is my knowledge blind spot, specially record usage, deepen memory. If you have different views, welcome to discuss together.
Let’s talk about the use of function transfer from an application scenario: instant chat function of wechat applet, from the home page to pass a method to get userInfo to the sub-component, onGetUserInfo method defined in the home page, but in the sub-component call, can also get the desired value.
Child component: Chatroom, passing function onGetUserInfo.
index.wxml
<chatroom
style="width: 100%; height: 100%"
envId="{{chatRoomEnvId}}"
collection="{{chatRoomCollection}}"
groupId="{{chatRoomGroupId}}"
groupName="{{chatRoomGroupName}}"
userInfo="{{userInfo}}"
onGetUserInfo="{{onGetUserInfo}}" // Pass the function as an attribute to the child component
getOpenID="{{getOpenID}}"
></chatroom>
Copy the code
index.js
// The method defined on the home page to get userInfo
onGetUserInfo: function(e) {
if (!this.logged && e.detail.userInfo) {
this.setData({
logged: true.avatarUrl: e.detail.userInfo.avatarUrl,
userInfo: e.detail.userInfo
})
}
},
Copy the code
To use this function in Chatroom:
chatroom.wxml
<button
open-type="getUserInfo"
bindgetuserinfo="onGetUserInfo"
class="userinfo"</button>Copy the code
chatroom.js
properties{
onGetUserInfo: {
type: Function,}}methods: {
onGetUserInfo(e) {
this.properties.onGetUserInfo(e)
},
}
Copy the code
For your convenience, most of the redundant code is omitted, only part of the core code is posted, if you want to see the details of the code, please go to the official website.