简单情景的页面回退
this.$router.go(-1);



复杂情景下的页面回退,就没有这么简单了。

用 Vue 开发单页应用时,会遇到这种需求情景:跳新页面去筛选、跳新页面去切换活动类型、跳新页面去搜索等等所有跳新页面,拿到值再跳回,进而操作左上角回退。既要保证拿到选中的筛选项回来,又要保证页面回退正常。

具体情景如下:

点了一路的页面,A =》 B =》 C =》 D =》 E ,此时【E页面】里点击【筛选icon】,点击之后跳转【筛选页】,选了筛选项之后跳回【E页面】,然后点击左上角的【回退icon】,不停回退,要求依次回退直到A页。
要求,项目中多个页面共用【筛选页】,选完筛选项之后要跳回对应的页面。

以上情景,你是不是想到了以下解决方案:

  1. 哪个页面(来源页)跳去的【筛选页】,跳转路由里就带个变量过去用以区分和跳回。
  2. 【筛选页】里选完把值存vuex里并this.$router.go(-1),然后,在来源页watch里监听路由,判断from.path 为【筛选页】路由的时候,获取vuex里的值请求接口。

上面两个解决方案:

  • 方案1 弊端明显,如果引用【筛选页】组件的页面太多,每个来源页路由上都要加这样的一个变量,且从【筛选页】跳回之后不停回退,会退回到【筛选页】之后再回退才能依次回到A。
  • 方案2 倒是可以试试,但是较麻烦。

上面两种方法是不是想想就很无力,既要保证拿到选中的筛选项回来,又要保证页面回退正常,并结合页面原本带的参数一起去查接口。

大兄弟,有个炒鸡简单的解决方案,那就是Vue-Router 的 replace方法。

跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。

而你要做的就是: 在 跳转【筛选页】的事件里、【筛选页】中点击【确定】跳回【来源页】的事件里 、【筛选页】左上角的回退事件里,路由跳转写法都用 replace

this.$router.replace({
	path:'/xxx',
	query:{xx:xx , yy:yy}
})
不要用this.$router.push() ,push方法会把路由加到历史记录里,而回退操作跳转的都是历史记录里的路由。

然后,除了筛选页以外的其他页面,左上角的回退icon的事件里,像往常一样,都用 this.$router.go(-1); 即可。



举个栗子

比如有管理页customerManage.vue 有个筛选页filterPage.vue
customerManage.vue 组件里:

<script>
export default {
	data(){
		return {}
	},
	methods: {
		 // 跳转筛选页
	     handleFilter() {
	       this.$router.replace({
	         path: "/filterPage",
	         query: {
	           jumpfrom: "customerManage"
	         }
	       });
	     },
		// 页面回退
		 handleHeaderLeftBtn() {
		   	this.$router.go(-1);
		 }
	 }
 }
 </script>



filterPage.vue 组件里:

<script>
export default {
	data(){
		return {
			jumpfrom:'', // 标识从哪个页面跳来
			filterCountryObj: {
	          name: "countryNo",
	          optionNo: "",
	          optionVal: "国家",
	           list: [],
	        },
	        filterProvinceObj: {
	          name: "provinceNo",
	          optionNo: "",
	          optionVal: "省份",
	          list: [],
	        },
	        filterCityObj: {
	          name: "cityNo",
	          optionNo: "",
	          optionVal: "城市",
	          list: [],
	        },
		}
	},
	methods: {
	   // 点击确定
	      handleOk() {
	        let param = {
	          currentHandle: 'filter'
	        };
	        let theQuery = this.$route.query;
	        delete theQuery.jumpfrom;
	        Object.assign(param, theQuery);
	
	        let theList = ['filterCountryObj', 'filterProvinceObj', 'filterCityObj'];
	       for (let i = 0; i < theList.length; i++) {
	          let obj = theList[i];
	          if (this[obj].choosedNo !== '') {
	            param[this[obj].name] = this[obj].choosedNo;
	          }
	        }
	        let jumpfrom = this.jumpfrom;
	        this.$router.replace({
	          path: `/${jumpfrom}`,
	          query: param
	        });
	      },
	
		// 页面回退
	    handleHeaderLeftBtn() {
	      let jumpfrom = this.jumpfrom;
	      let param = this.$route.query;
	      delete param.jumpfrom;
	      this.$router.replace({
	        path: `/${jumpfrom}`,
	        query: param
	      });
	    }
	 }
 }
 </script>