The pit in WeChat applet

There will be many pits in the process of developing small programs. After a long time, they will be forgotten. First, write down the ones that you can remember, and then add them when you have time.

Pit 1: The function does not return a value

Code first:

Page({
    data: {
        name:""
    },

    onLoad: function (options) {
        var name = this.myFunc();
        this.setData({"name":name});
    },

    myFunc:function(){
        return "test";
    }
})

When I wrote this code before, I found that the name was undefined. Helpless can only be changed to the callback method:

Page({
    data: {
        name:""
    },

    onLoad: function (options) {
        var oThis = this;
        this.myFunc(function(name){
            oThis.setData({"name":name});
        });
    },

    myFunc:function(fn){
        fn("test");
    }
})

Pit 2: The data in Data must use setData

Paste code:

Page({
    data: {
        cond:{
            pageIndex:0
        }
        
    },

    onLoad: function (options) {
        var oThis = this;
        var cond=this.data.cond;
        cond.pageIndex++;
        $.api("api路径",{pageindex:pageindex})
            .then(function(value){
                if( this.data.cond.pageIndex>0){
                    //do something
                    console.log("pageindex="+this.data.cond.pageIndex);
                }
            });
    }
})

The reason is that pageIndex is just a query parameter and has nothing to do with UI, so I don't want to use setData, but modify it directly. It turns out that its value has not changed at all, that is, the reference to cond is not a reference, but a value! When var cond=this.data.cond, cond is actually a copy of this.data.cond, not an object reference.

It can be seen from the pit that the syntax of the applet is just like javascript, but it is not javascript at all.

{{o.name}}
{{m.name}}

Guess you like

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