页面生命周期onShow没有触发

现象描述:

  通过router.push接口跳转到快应用的B页面,当B页面只是引用一个自定义组件XX的时候,B页面的onShow生命周期无法触发。如下图所示:

代码如下:

      B页面代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<import name="listone" src="./aa.ux"></import>
<template>
  <!-- template里只能有一个根节点 -->
<listone></listone>
</template>
<script>
  import prompt from '@system.prompt'
  export default {
    private: {
    },
    onInit: function () {
    },
    onShow() {
      console.log('我显示了我显示了我显示了我显示了');
      prompt.showToast({
        message: '我显示了我显示了我显示了我显示了'
      })
    }, //无法触发
  }
</script>
  
<style>
  .demo-page {
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  
  .title {
    font-size: 40px;
    text-align: center;
  }
</style>

自定义组件aa.ux:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
  <div class="container">
    <text>天气不错啊</text>
    <text>天气不错啊</text>
    <text>天气不错啊</text>
    <text>天气不错啊</text>
  </div>
</template>
<style>
 .container {
    flex-direction: column;
    justify-content: center;
align-items: center;
#00fa9a;
  }
</style>
<script>
  module.exports = {
    data: {
    },
    onInit() {
    },
  }
</script>

问题分析:

快应用引擎框架决定了自定义组件作为B页面的根节点时,B页面的onShow生命周期是无法触发的,但是子组件自身的onShow可以触发。

解决方案:

在B页面的子组件外面加个div组件作为根节点,而不是把自定义组件作为根节点,这样B页面的onShow生命周期就可以触发了。

B页面修改后代码如下(见红色部分):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<import name="listone" src="./aa.ux"></import>
<template>
  <!-- template里只能有一个根节点 -->
  <div>
    <listone></listone>
  </div>
  
</template>
<script>
  import prompt from '@system.prompt'
  export default {
    private: {
    },
    onInit: function () {
    },
    onShow() {
      console.log('我显示了我显示了我显示了我显示了');
      prompt.showToast({
        message: '我显示了我显示了我显示了我显示了'
      })
    },
  }
</script>
  
<style>
  .demo-page {
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  
  .title {
    font-size: 40px;
    text-align: center;
  }
</style>

修改后代码如下图所示:

欲了解更多详情,请参见:

快应用生命周期:

https://developer.huawei.com/consumer/cn/doc/development/quickApp-References/quickapp-script#h2-1575381018573

原文链接:https://developer.huawei.com/...
原作者:Mayism

原文地址:https://www.cnblogs.com/developer-huawei/p/15048925.html