【mpvue】微信小程序调用switchTab重定向到页面,不会自动刷新,调用page.onLoad()方法也没有效果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shine_a/article/details/88319554

1、小程序效果演示

(1)点击添加基金按钮,跳转到添加基金的页面,目前该页面(pages/index/main)有两个基金。

(2)在添加基金页面填写基金代码,会跳出弹框是否继续添加基金

(3)点击取消,会自动跳转到首页,显示刚刚添加的基金

2、需求描述,在添加基金页面添加完基金之后,点击showModal提醒框的取消按钮,自动跳转到首页并自动刷新首页,显示出刚刚添加的基金(/pages/index/main)

错误示范
像下面这样写首页不会自动刷新

wx.showModal({
  title: '成功',
  confirmText: '继续',
  content: `${res.code}(${res.name})添加成功,要继续添加基金吗?`,
  success: function (res) {
    if (res.cancel) {
      wx.switchTab({
        url: '/pages/index/main'
      })
    }
  }
})

根据百度查询的建议,获取到首页并调用page.onLoad()就可以实现自动刷新,但是还是没有效果,像下面这样写的

wx.showModal({
  title: '成功',
  confirmText: '继续',
  content: `${res.code}(${res.name})添加成功,要继续添加基金吗?`,
  success: function (res) {
    if (res.cancel) {
      wx.switchTab({
        url: '/pages/index/main',
        success: function (e) { 
          var page = getCurrentPages().pop();
          console.log('page',page)
          if (page == undefined || page == null) return;
          page.onLoad();
        } 
      })
    }
  }
})

3、通过page.onPullDownRefresh()来解决自动刷新的问题

(1)首先将page.onLoad();改成page.onPullDownRefresh();

wx.showModal({
  title: '成功',
  confirmText: '继续',
  content: `${res.code}(${res.name})添加成功,要继续添加基金吗?`,
  success: function (res) {
    if (res.cancel) {
      wx.switchTab({
        url: '/pages/index/main',
        success: function (e) { 
          var page = getCurrentPages().pop();
          console.log('page',page)
          if (page == undefined || page == null) return;
          page.onPullDownRefresh();
        } 
      })
    }
  }
})

(2)再在pages/index/index.vue文件中添加上onPullDownRefresh,其中this.getFunds()是我在methods中定义的获取目前添加的所有基金的方法。

<script>
export default {
  onPullDownRefresh () {
	this.getFunds()
	wx.stopPullDownRefresh()
  }
}
</script>

(3)在pages/index/main.json中添加代码"enablePullDownRefresh":true,设置允许下拉刷新

{
  "enablePullDownRefresh":true
}

这样添加完基金,返回到显示基金的页面,就会显示刚刚添加的基金了。

猜你喜欢

转载自blog.csdn.net/shine_a/article/details/88319554