三种跳转页面传参方式


实现页面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