前言
最近在开发 uniapp 的 h5 项目,按着正常的逻辑来说启动 h5 页面,先触发 App.vue 中的 onLaunch 生命周期,随后触发首页的 onLoad 。但其实不是,在触发 onLaunch 的同时也在触发要进入页面的 onLoad ,所以导致在 onLoad 里面拿不到 onLaunch 里的数据。
解决方法:
main.js:
Vue.prototype.$onLaunched = new Promise((resolve) => {
Vue.prototype.$isResolve = resolve;
});
App.vue:
<script>
export default {
onLaunch: function () {
this.getDict();
},
onShow: function () {},
onHide: function () {},
methods: {
async getDict() {
// 调用接口设置vuex字典并存到缓存里
await this.$store.dispatch("getDictData");
// 在业务代码最终加上这行代码
this.$isResolve();
},
},
};
</script>
index.vue:
async onLoad() {
await this.$onLaunched;
this.getDict();
},
methods:{
getDict(){
// 此时可以获取缓存中的字典
console.log(JSON.parse(uni.getStorageSync("dictName")))
}
}