Five methods of data transfer between applet pages

Five methods of data transfer between applet pages

  1. wx.navigateTo()When using , splicing in url, this method is suitable for the case of small amount of data

    Before the jump, the page A splices the parameters in the url, ?separates , =connects the parameter key and the parameter value with , and &separates ;

    wx.navigateTo({
          
          
        url: '/somePathXXX/somePathXXX?keyA=valueA&keyB=valueB'
    })
    

    Jump to page B and receive it in the lifecycle function onLoad

    onLoad: function (options) {
          
          
        let keyA = options.keyA
        let keyB = options.keyB
    },
    

    If you need to pass an object or array, you need to convert the object or data into a JSON string first

    let data = {
          
          
        name: 'sun',
        sex: '女',
        age: 20
    }
    let dataStr = JSON.stringify(data)
    wx.navigateTo({
          
          
      url: '/somePathXXX/somePathXXX?dataStr=' + dataStr,
    })
    

    Convert back to object or array when received

    onLoad: function (options) {
          
          
        let data = JSON.parse(options.dataStr)
        console.log(data); // {name: "sun", sex: "女", age: 20}
    },
    
  2. wx.navigateTo()When using , transmit data to the opened page through eventChannel, or transmit data to the original page from the opened page, which is suitable for data transmission with large amount of data or relatively complex data

    ① Page A jumps to page B, and at the same time, page A transmits data to page B

    Page A before the jump:

    let data = {
          
          
        name: 'sun',
        sex: '女',
        pats: [ 'cat', 'dog', 'fish' ],
        address: {
          
          
            province: '山东省',
            city: '青岛市'
        } 
    }
    wx.navigateTo({
          
          
        url: '/pages/eventChannel-demoB/eventChannel-demoB',
        success: function (res) {
          
          
            res.eventChannel.emit('pageBEvent', data) 
        }
    })
    

    After the jump, page B is received in the life cycle function onLoad (it can also be received in other life cycle functions, or at any other stage. The test result is that page B cannot be received repeatedly, but can only be received once, even in different methods)

    onLoad: function (options) {
          
          
        const eventChannel = this.getOpenerEventChannel();
        // 监听 pageBEvent 事件,获取上一页面通过 eventChannel 传送到当前页面的数据
        eventChannel.on('pageBEvent', (params) => {
          
          
            console.log(params);
        });
    },
    

    ② Page A jumps to page B, and page B transmits data to page A

    Page A before the jump:

    wx.navigateTo({
          
          
        url: '/pages/eventChannel-demoB/eventChannel-demoB',
        events: {
          
          
            // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
            acceptDataFromOpenedPage: function(data) {
          
          
                console.log(data)
            },
            someEvent: function(data) {
          
          
                console.log(data)
            }
        }
    })
    

    Page B (can also trigger A page in other life cycle functions, or other methods at any stage, pass data, and different from receiving parameters, the events in the events that trigger A page can be any number of times, and the data passed each time can be different):

    onLoad: function (options) {
          
          
        const eventChannel = this.getOpenerEventChannel();
        // 触发A页面的事件并传递数据
        eventChannel.emit('acceptDataFromOpenedPage', {
          
          data: 'test111'});
        eventChannel.emit('someEvent', {
          
          data: 'test222'});
    },
    

    ③ EventChannel can also directly establish data channels on multiple pages of ABC.

    //可以保存在getApp()全局实例中以备其他页面使用
    // 保留AB通道事件,已备C页面给A页面发送数据
    // B页面
        const eventChannel = this.getOpenerEventChannel()
        getApp().pageBEventChannel = eventChannel
    //C页面 触发A页面的事件并传递数据
     getApp().pageBEventChannel.emit('acceptDataFromOpenedPage', {
          
           data: 'Page C->A' });
    
  3. Return to the previous page while passing data

    If you need to transfer data to page A when returning from page B to page A, you can use this method

    on page B

    goBack: function () {
          
          
        let backData = {
          
          
            name: 'Lily',
            age: 18,
            address: {
          
          
                province: '山东省',
                city: '青岛市',
            },
            pets: ['dog','cat']
        }
        var pages = getCurrentPages();//获取当前页面栈。数组中第一个元素为首页,最后一个元素为当前页面。
        var prevPage = pages[pages.length - 2]; //获取上一个页面
        //直接调用上一个页面的setData()方法,把数据存到上一个页面中去
        prevPage.setData({
          
          
            backData: backData
        })
        console.log(prevPage.__data__.backData);//数据已存在prevPage.__data__.backData中
        wx.navigateBack()
    },
    

    Obtain the returned value on page A (it can also be obtained repeatedly at any stage after onShow)

    onShow: function () {
          
          
        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1];
        let backData = currPage.__data__.backData; // 此处既是上一页面传递过来的值
        console.log(backData);
    },
    

    Note: Do App.onLaunchnot call when getCurrentPages(), the page has not been generated yet

  4. Use local cache wx.setStorageSync()

    Store the data at the specified key in the local cache. The content corresponding to the original key will be overwritten. Unless the user actively deletes or is cleared by the system due to storage space reasons, the data is always available. The maximum data length allowed for a single key is 1MB, and the upper limit for all data storage is 10MB.

    The data stored in this way is public data, which can be stored and modified anywhere. After modification, it will take effect globally and can be obtained anywhere.

    //储存
    wx.setStorageSync('someKey', {
          
           name: 'lily' }),
    //需要时获取指定key
    console.log(wx.getStorageSync('someKey')); // {name: 'lily'}
    //修改指定key
    wx.setStorageSync('someKey', {
          
           name: 'nana' }),
    //移除指定key
    wx.removeStorageSync('someKey')
    //移除全部key
    wx.clearStorageSync()
    

    Note: The difference between setStorage and setStorageSync : setStorage is asynchronous, while setStorageSync is synchronous.

    When the subsequent operations must depend on the modified storage data, you need to use synchronization, that is, setStorageSync, otherwise when the subsequent operations are executed, the data that has not been updated is still used.

    When the subsequent operations do not need to use the modified storage data, then there is no need to synchronize immediately. At this time, you can choose to use asynchronous, that is, setStorage, because the operation of memory takes time, and it is often not as fast as the code.

  5. Add public data in app.js

    Each applet needs app.jsto call App()the method in to register the applet instance. In the parameterApp(object) of the method , the developer can add any function or data variable. On other pages , the globally unique App instance can be obtained through the method, and the data on the App can be obtained. Or call a function registered by the developer on .objectgetApp()App

    The data stored in this way is public data, which can be stored and modified anywhere. After modification, it will take effect globally and can be obtained anywhere.

    In app.js:

    App({
          
          
      globalData: {
          
          
          name: 'globalName'
      },
      globalString: 'globalStringXXX',
      },
      // 其他……
    })
    

    Obtained in the page (it can also be obtained in the lifecycle function onLoad):

    let app = getApp()
    console.log(app.globalData); // {name: 'globalName'}
    console.log(app.globalString); // globalStringXXX
    

    Revise:

    let app = getApp()
    app.globalString = '修改后的stringXXX'
    console.log(app.globalString); // 修改后的stringXXX
    

Guess you like

Origin blog.csdn.net/weixin_44001906/article/details/127106277