Vue.js 编程式导航-跳转传参

Vue.js 编程式导航-跳转传参

  • 利用path路径跳转传参
    • 1.path路径跳转 (适合path路径短的场景)
    • 2.path路径传参
      • (1)查询参数传参(query 适合传多个参数)
      • (2)动态路由传参(params 适合传单个参数)
  • 利用name命名跳转传参
    • 1.name命名跳转(适合path路径长的场景)
    • 2.name命名传参
      • (1)查询参数传参(query 适合传多个参数)
      • (2)动态路由传参(params 适合传单个参数)

利用path路径跳转传参

假设创建了一个路由对象

// 创建了一个路由对象
const router = new VueRouter({
  routes: [
    { path: '/home', component: Home },
    { path: '/search', component: Search },
  ]
})

1.path路径跳转 (适合path路径短的场景)

简洁写法 和 完整写法

this.$router.push('路由路径')
 this.$router.push({   
        path:'路径',
      })

示例1和示例2

this.$router.push('/search')
 this.$router.push({
         path:'/search',
       })

2.path路径传参

(1)查询参数传参(query 适合传多个参数)

1.简洁写法 和 完整写法

this.$router.push('路由路径?参数名1=参数值1&参数名2=参数值2')
this.$router.push({   //[完整写法] 更适合传参
        path:'/路径',
        query:{
           参数名1:'参数值1',
           参数名2:'参数值2'
         }
      })

示例1 和 示例2

this.$router.push('/search?key=1')
 this.$router.push({
         path:'/search',
         query:{
           key:1
         }
       })

2.在另一个组件如果要接收的话则采取

$route.query.参数名   //获取查询参数

(2)动态路由传参(params 适合传单个参数)

1.先配置动态路由后面加:参数名
示例

  { path: '/search/:words', component: Search },

2.简洁写法 和 完整写法

 this.$router.push('/路径/参数值')
 this.$router.push({
      path:'/路径/参数值'
 })

示例1 和 示例2

this.$router.push('/search/1')
 this.$router.push({
         path:'/search/1',
       })

3.在另一个组件如果要接收的话则采取

$route.params.参数名 获取动态路由参数

利用name命名跳转传参

假设创建了一个路由对象

// 创建了一个路由对象
const router = new VueRouter({
  routes: [
    { path: '/home', component: Home },
    { path: '/search', component: Search },
  ]
})

1.name命名跳转(适合path路径长的场景)

1.先给路由起名字,再用名字跳转

{ name: 'search', path: '/search', component: Search },
 this.$router.push({
         name:'路由名',
 })

示例

 this.$router.push({
         name:'search',
       })

2.name命名传参

(1)查询参数传参(query 适合传多个参数)

1.先给路由起名字

{ name: 'search', path: '/search', component: Search },

1.写法

this.$router.push({   
        name:'路由名',
        query:{
           参数名1:'参数值1',
           参数名2:'参数值2'
         }
      })

示例

 this.$router.push({
         name:'search',
         query:{
           key:1
         }
       })

2.在另一个组件如果要接收的话则采取

$route.query.参数名   //获取查询参数

(2)动态路由传参(params 适合传单个参数)

1.先配置动态路由后面加:参数名
示例

  { name: 'search', path: '/search/:words', component: Search },

2.写法

this.$router.push({   
        name:'路由名',
        params:{
           参数名:'参数值',
         }
      })

示例

 this.$router.push({
         name:'search',
         params:{
           words:1
         }
       })

3.在另一个组件如果要接收的话则采取

$route.params.参数名   //获取查询参数

你可能感兴趣的:(vue.js,前端,javascript)