How to implement two-way data binding in WeChat applet
In the development of native small programs, the data flow is one-way and cannot be bound in two directions, but it is quite simple to implement the two-way binding function!
The following is about the principle of two-way binding in the mini program framework minapp. In minapp, you only need to add .sync after the attribute name of the component in the wxml template to achieve it. Two-way binding. In order to explain the principle below, the process may be slightly complicated, but in fact, the minapp framework has already handled those complicated details!
First of all, To enable two-way binding of data, excessive data sources should be avoided.
When data flows naturally from top to bottom, if each component maintains its own data while keeping their data values consistent, although this can be done, the implementation process will not be simple. .
But there is no need to use mobx or redux to manage data globally in order to have a unified data source. This feels like overkill.
Since two-way binding only exists between parent and child components, and data is passed from parent to child, you can preferentially use the data in the parent component as the data source.
Each time the child component updates the data, it does not Update its own internal data, but trigger the parent component to update its data through the event mechanism. After the parent component updates the data, it will naturally pass the updated data to the child component.
Thus Achieve two-way flow of data!
Not all data requires two-way binding, and not all data is external. Subcomponents can also have their own internal data. So this involves the second question we want to talk about: Distinguish which data needs two-way binding and which data needs to be maintained by the sub-components themselves.
Anyone who has used vue should know that to achieve two-way binding in vue, special processing needs to be done in the template. For example, if you want to bidirectionally bind the parentAttr
of the parent component to the childAttr
of the child component, you need to write this in the template of the parent component:
<child></child>
But the applet does not Without such a simple syntax, characters such as "." are not even allowed to appear in the attribute names of the wxml language of the applet. Back to our problem, The sub-component needs to know which attributes require two-way binding and which attributes need to be maintained by itself.
Add a field to the template (syncAttrMap
) to specifically tell The child component needs two-way binding of the dataset. Can't it just be combined? For example, the above example can be written as a writing method supported by WeChat applet:
<child></child><child></child>
Then, you need to deal with the problem of subcomponent data update. There are two parts of data in the subcomponent, Part of it is internal data, and the other part is the data in the parent component.
The child component can get which data is internal data and which data is the parent component's data by reading the attribute syncAttrMap
, and can Know what the key name of the data in the parent component corresponding to
is. Since the native component method setData
does not care whether it is internal data or data in the parent component, as long as
you call it to update the data, it will only update the internal data. Therefore, a new method needs to be implemented to automatically determine the data source. If it is internal data,
directly call setData
; if it is parent component data in two-way binding, an event can be triggered. Notify the parent component to update the corresponding value.
So according to the above description, the parent component needs to have a listening function , and the child component needs to have a smart setData
function. Instead of naming the parent component's listening function
as onSyncAttrUpdate
and the child component's smart setData
function as setDataSmart
, you can have the following code:
// 父组件Component({ methods: { onSyncAttrUpdate(e) { this.setData(e.detail) // 子组件传来的需要更新的数据 } }})
<child></child>
// 子组件Component({ properties: { childAttr: String, syncAttrMap: String }, methods: { // 子组件更新数据时,只要调用此方法即可,而不是 `setData` setDataSmart(data) { // splitDataBySyncAttrMap 函数的实现过程就不说了,只是将对象拆分,大家应该都能实现 let {parentData, innerData} = splitDataBySyncAttrMap(data, this.data.syncAttrMap) // 内部数据使用 setData 更新 if (Object.keys(innerData).length) { this.setData(innerData) // setData 中还支持 callback 的回调,为了简化代码,这里不讨论 } // 双向绑定的父组件数据触发事件让父组件自己去更新 if (Object.keys(parentData).length) { this.triggerEvent('syncAttrUpdate', parentData) } } }})
At this point, a simple two-way binding function is completed. However, since sub-components may also contain other components, that is to say, sub-components can also be parent components, and parent components can also be
child components. Therefore, the above onSyncAttrUpdate
setDataSmart
function needs to be implemented in each component, so
define a public object BaseComponent
to implement all the above functions ,like:
// BaseComponentconst BaseComponent = { properties: { syncAttrMap: String }, methods: { setDataSmart() { // ... }, onSyncAttrUpdate() { // ... } }}
然后将 BaseComponent minin 到每个组件的对象上去就可以了;另外小程序中还有一个特殊的组件:Page,虽然 Page 和 Component 结构是两样的,
但它也应该算是一个组件,不过它一定是父组件,不可能是别的组件的子组件,所以还需要将 onSyncAttrUpdate
方法写了所有的 Page 定义中。
所有这些就是 minapp 的双向绑定的基本原理了。
等等,最后还有一件事:wxml 模板,不能让用户每次写双向绑定的时候都要写那么复杂语句吧?当然不用,minapp 在编译时,会将模板做个简单的转化:
<child></child><child></child>
谢谢,文章到此结束,欢迎关注 minapp:重新定义微信小程序的开发
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to implement two-way data binding in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

If you need to know how to use filtering with multiple criteria in Excel, the following tutorial will guide you through the steps to ensure you can filter and sort your data effectively. Excel's filtering function is very powerful and can help you extract the information you need from large amounts of data. This function can filter data according to the conditions you set and display only the parts that meet the conditions, making data management more efficient. By using the filter function, you can quickly find target data, saving time in finding and organizing data. This function can not only be applied to simple data lists, but can also be filtered based on multiple conditions to help you locate the information you need more accurately. Overall, Excel’s filtering function is a very practical

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects
