現象描述:
通過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