uniapp 开发h5 浏览器返回不走任何生命周期,但是你需要每次进入页面都执行一些方法那如何解决?
有问题不可怕,可怕的是百度不到一个可以落地的方案那就很头疼
可以说是认真看完了大部分博客,还是没有解决我的问题那感觉就像就像
如果你也有同样的问题,可以看看下面我解决这个问题的思路,当然如果你有更好的解决方案,一定要cue 我一下 毕竟我的目的不仅是让代码跑起来,还有一丝倔强
我的使用场景
在点击不同险种的时候,去选择不同的小险种去投保
在没做处理的时候 发现浏览器返回再次选择不同的险种进入,参数不同但是页面还是之前的
代码处理
我是通过vue 路由跳转的 如下 叫做A页面需要跳到B页面
B页面接受参数
是通过在页面中执行getCurrentQuery方法来执行想要执行的逻辑
<template>
<div class="choiceDetail_box">
{{pageTitle}}{{getCurrentQuery()}}
</div>
</template>
<script>
import { fetch } from '../../common/request';
import moment from 'moment';
export default {
data() {
return {
pageTitle:''
}
},
mounted() {
},
methods: {
getCurrentQuery(){
const { title } = this.$route.params
this.pageTitle=title
document.title=title
}
},
}
</script>
<style scope>
</style>
在这个时候的 每次进入页面就可以刷新不同的参数以及可以在getCurrentQuery执行相关逻辑
此时可能还有一个问题就是从B页面返回A页面的时候也无法触发相关的生命周期,如果你需要在返回的时候 也处理相关逻辑可以参考下代码
比如我返回A页面时候需要重置 A页面的title
使用 window.addEventListener('popstate', this.getPagetitle) 监听浏览器的返回在getPagetitle方法中做一些逻辑处理
// A页面
mounted() {
document.title='选择险种'
console.log('ckx debug 生命周期 ')
window.addEventListener('popstate', this.getPagetitle);
},
methods: {
selectComapny(index){
this.insuranceList.map(item=>item.selected=false)
this.insuranceList[index].selected=true
},
choiceDetail(title) {
console.log(title);
this.$router.push({
path:'/pages/smartCarInsurance/choiceDetail',
params:{
title,
}
})
},
getPagetitle(){
console.log('ckx debug 监听浏览器返回 ')
document.title='选择险种'
}
}
至此 基本实现了我的需求
最后
如果有更好的处理方法 就cue我一下