vue路由传参

方案一 路由配置设置参数

问题:参数直接在地址栏中显示

从 about组件跳转至home组件

about 组件



jumpToHome(id){  
  this.$router.push({
     path: `/home/${id}`,
  })
}

home 组件

    export default {
          name: 'Home' ,
          data(){
               return{
                  getParam:''
               }
          },
          mounted(){
            this.getParam = this.$route.params.id || ''; 
          } 
    }

路由配置

    const routes = [ 
        {
            path: '/',
            name: 'Home',
            component: Home
        },
          {
            path: '/home/:id', /* 路由中的配置参数与组件中保持一直 */
            name: 'Home',
            component: Home
          },
          {
            path: '/about',
            name: 'About',
            component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
          }
    ]

代码片段
vue路由传参_第1张图片
vue路由传参_第2张图片

方案二 params

问题:页面刷新会导致参数失效。

about组件


export default {
  name: 'About',
  methods:{ 

    jumpToHome(){  
       this.$router.push({
          name: 'Home',
          params: {
            id: 'test1123'
          }
        })
    }
  } 
}

home组件

export default {
  name: 'Home' ,
  data(){
   return{
      getParam:''
   }
  },
  mounted(){
    this.getParam = this.$route.params.id || ''; 
  } 
   
}

路由配置

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import( '../views/About.vue')
  }
]

代码片段
vue路由传参_第3张图片
vue路由传参_第4张图片

方案3 path + query

问题:参数在url中显示

about组件

jumpToHome(){  
   this.$router.push({
      path:'/home',
      query: {
        id: 'testquery100'
      }
    })
}

home组件

 mounted(){ 
    this.id = this.$route.query.id || ''; 
  } 

路由配置

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import( '../views/About.vue')
  }
]

代码片段
vue路由传参_第5张图片
vue路由传参_第6张图片

你可能感兴趣的:(vue路由传参)