今天在實現一個小功能的時候,遇到一個問題,使用vue-router獲取上一頁面的url信息,我嘗試了多種方式,發現使用vue-router的canDeactivate鈎子實現這個功能最為方便,現在將我的實現代碼總結如下:
項目使用的是vue-cli,直接貼代碼
export default { mixins: [], vuex: { actions: {fetchCertificates}, }, data() { return {} }, route: { data() { this.$root.showLoading(); return this.fetchCertificates().then((res) => { this.$root.dismissLoading(); if (res.error) return this.$root.toastError(res.error); if(res.data.certificates.length >0){ return res.data; }else{ console.log(this.$route ,"----當前頁面的url信息----"); } }); }, canActivate (transition) { console.log(transition,"======上一個頁面的url信息======="); transition.next(); } }, }