How to implement two-way data binding in native WeChat applet

Official website: https://qiu8310.github.io/minapp/

Author: Mora

In the development of native applets, the data flow is one-way and cannot be bound in two directions, but it is quite simple to realize the function of two-way binding!

The following is the principle of implementing two-way binding in the applet framework minapp . In minapp , you only need to add .syncto implement two-way binding. In order to explain its principle, the process may be a little more complicated, but in fact, the minapp framework has already dealt with those complicated details!

First, to make data two-way bound, you should avoid too many data sources . In the case of data flowing naturally from top to bottom, if each component maintains its own data, and maintains the consistency of their data values, this can be done, but the implementation process is not simple. But there is no need to say that in order to have a unified data source, use mobx or redux to manage data globally, which is a bit like killing a chicken with a knife. Since two-way binding only exists between parent and child components, and data is passed from parent to child, the data in the parent component can be used as the data source first, and the child component does not update its own internal data every time the data is updated. , but triggers the parent component to update its data through the event mechanism, and after the parent component updates the data, it will naturally pass the updated data to the child component, thus achieving a two-way flow of data!

data-stream

Not all data requires two-way binding, and not all data is external, and 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 subcomponents 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, to bind the parent component parentAttrtwo-way to the child component childAttr, you need to write this in the template of the parent component:

<child childAttr.sync="parentAttr" />

But the applet does not have such a simple syntax, and even characters such as " . " are not allowed in the attribute name of the wxml language of the applet. Back to our question, subcomponents need to know which properties need to be bound in both directions, and which properties need to be maintained by themselves. Wouldn't it be enough to add a field ( syncAttrMap) to the template specifically to tell subcomponents the data collection that requires bidirectional binding. For example, the above example can be written in the way supported by WeChat applet:

<child childAttr="{{parentAttr}}" syncAttrMap="childAttr=parentAttr" />

<!--
  如果同时存在多个双向绑定和不需要双向绑定的属性时,可以写成下面这样:
  p1, p2 分别双向绑定到子组件的 c1, c2,而 p3 单向绑定到 c3 上
-->

<child c1="{{p1}}" c2="{{p2}}" c3="{{p3}}" syncAttrMap="c1=p1&c2=p2" />

Next, we need to deal with the problem of updating the data of the subcomponent. There are two parts of data in the subcomponent, one is the internal data, and the other is the data in the parent component. The subcomponent syncAttrMapcan . data, which data is the data of the parent component, and you can know what the key name of the data in the corresponding parent component is. Since the native component method setDatadoes not care whether you are internal data or the 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, it will be called directly setData; if it is the parent component data in two-way binding, an event can be triggered to notify the parent component to update the corresponding value.

So according to the above description, the parent component needs a listener function, and the child component needs a smart setDatafunction . If you name the listener function of the parent component and onSyncAttrUpdatethe smart setDatafunction as setDataSmart, you can have the following code:

// 父组件
Component({
  methods: {
    onSyncAttrUpdate(e) {
      this.setData(e.detail) // 子组件传来的需要更新的数据
    }
  }
})

<!-- 父组件的模板 -->
<child childAttr="{{parentAttr}}" syncAttrMap="childAttr=parentAttr" bind:syncAttrUpdate="onSyncAttrUpdate" />
// 子组件
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 a child component may also contain other components, that is to say, a child component can also be a parent component, and a parent component can also be a child component. So the above onSyncAttrUpdate setDataSmartfunction needs to be implemented in each component, so it is not necessary to define a public object BaseComponentto implement all the above functions, such as:

// BaseComponent
const BaseComponent = {
  properties: {
    syncAttrMap: String
  },
  methods: {
    setDataSmart() {
      // ...
    },
    onSyncAttrUpdate() {
      // ...
    }
  }
}

Then you can minin the BaseComponent to the object of each component; in addition, there is a special component in the applet: Page , although the structure of Page and Component are different, it should also be regarded as a component, but it must be the parent Components cannot be subcomponents of other components, so you also need to write the onSyncAttrUpdatemethod in all Page definitions. All this is the basic principle of the two-way binding of minapp .

Wait, there's one last thing: wxml templates , can't let users write such complex statements every time they write two-way bindings? Of course not, when minapp compiles, it will simply convert the template:

<child childAttr.sync="parentAttr" />

<!-- 由于属性名 syncAttrMap 是固定的,所以完全可以通过编译手段,将上面的模板转成下面这个模板 -->

<child childAttr="{{parentAttr}}" syncAttrMap="childAttr=parentAttr" />

Thank you, this is the end of the article, welcome to pay attention to minapp: redefine the development of WeChat applet

Guess you like

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