【快应用】二级页面如何携带参数返回一级页面?

【关键词】

快应用、router、onBackPress

 

【问题背景】

页面栈有A、B两个页面,怎么在B页面中调A页面的方法或传参?场景是:A页面是列表页,B页面是详情页,B页面状态改变后返回A页面状态也要改变。

 

【解决方法】

在onBackPress里重写返回逻辑,通过router.push方式携带参数跳转,A页面在onshow里通过this.param获取(param是push传参的参数名)。

代码如下:

A页面:

<template>
  <!-- Only one root node is allowed in template. -->
  <div class="container">
    <text class="title">A的值是{{message}}</text>
    <input class="btn" type="button" value="跳转"  @click="onClick" />
  </div>
</template>

<style>
  .container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .btn {
    width: 140px;
    height: 60px;
    background-color: #00bfff;
    border-radius: 28px;
  }

  .title {
    font-size: 50px;
  }
</style>

<script>
  import router from '@system.router'
  module.exports = {
    data: {
      componentData: {},
      message: 'Hello World'
    },
    onInit() {
      this.$page.setTitleBar({
        text: 'PageA',
        textColor: '#ffffff',
        backgroundColor: '#007DFF',
        backgroundOpacity: 0.5,
        menu: true
      });
    },
    onShow(options) {
      '// Do something when show.'
      console.log(this.messageB + 'this.messageB')
   // messageB是B页面携带返回的参数
      this.message = this.messageB || this.message
    },
    onClick() {
        router.push({
          uri: '/pageB',
          params: {message: this.message}
        })
    }
  }
</script>

B页面:

<template>
  <!-- Only one root node is allowed in template. -->
  <div class="container">
    <text class="title">接收message:{{messageB}}</text>
    <input class="btn" type="button" value="改变message"  @click="onClick" />
  </div>
</template>

<style>
  .container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .btn {
    width: 300px;
    height: 60px;
    margin-bottom: 20px;
    background-color: #00bfff;
    border-radius: 75px;
  }

  .title {
    font-size: 50px;
  }
</style>

<script>
  import router from '@system.router'
  module.exports = {
    data: {
      componentData: {},
      messageB: ''
    },
    onInit() {
      this.$page.setTitleBar({
        text: 'PageB',
        textColor: '#ffffff',
        backgroundColor: '#007DFF',
        backgroundOpacity: 0.5,
        menu: true
      });
    },
    onShow(options) {
      '// Do something when show.'
      console.log(this.message + 'this.messageA')
   // message 是A页面传过来的值
      this.messageB = this.message
    },
    onClick() {
      this.messageB = 'Hello QuickApp'
    },
    onBackPress() {
        console.info(`Triggered:onBackPress`);
        router.clear()
        router.push({
          uri: '/hello',
          params: {messageB: this.messageB}
        })
    }
  }
</script>

效果图如下:

cke_1751.pngcke_2374.pngcke_3071.pngcke_3884.png

posted @ 2023-09-06 16:31  Mayism123  阅读(32)  评论(0编辑  收藏  举报