三種跳轉頁面傳參方式


實現頁面A(Home)->頁面B(Details)

1.動態路由通過路徑參數傳遞(router)

在index.js中定義路由並設置路由參數:

{
	path:'/details/:classid',
	name:'Details',
	component:()=>import('@/views/Details')
}

在組件A中發送路由跳轉請求(這里用到了ES6寫法):

this.$router.push(`/details/${classid}`);

 注:this.$router.push和<router-link to='xxx'>效果相同,只是一個是編程式寫法,一個是聲明式寫法,其他並無區別。

在組件B中接收參數:

created() {
    if (this.$route.params && this.$route.params.classid) {
      const classid = this.$route.params.classid;
      console.log(classid);
    }
  }

注:路由參數會自動添加到params,所以獲取時也是用this.$route.params來獲取。

2.通過query傳遞參數(router)

 在index.js中定義路由:

{
        path:'/details',
        name:'Details',
        component:()=>import('@/views/Details')
    }

注:使用query傳遞參數時,路徑里就不能設置路由參數了。

在組件A中發送路由跳轉請求:

this.$router.push({path: '/details', query: {classid}});

在頁面B中接收參數:

created() {
    if (this.$route.query && this.$route.query.classid) {
      const classid = this.$route.query.classid;
      console.log(classid);
    }
  }

注:通過query傳遞的參數自動放到query中,獲取時用this.$route.query來獲取。

3.通過sessionStorage本地存儲傳遞參數(Storage)

 在index.js中定義路由:同2

在組件A中發送路由跳轉請求:

sessionStorage.setItem('classid',classid);
this.$router.push('/details');

在組件B中接收參數:

created() {
    const classid = sessionStorage.getItem('classid');
    if (classid) {
      console.log(classid);
    }
  }

本地存儲查看參數方式:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM