5、路由传参

150 阅读1分钟

1、页面跳转的方式包括两种:

  • 声明式导航:通过router-link标签,必须要有to属性,来实现页面的跳转
  • 编程式导航:通过组件实例的router.pushrouter.push、router.replace等方法来实现页面的跳转

2、路由传参

  • params传参
  • query传参
// 字符串形式传递params参数
// 注意:需要在路由中进行占位。路由写法:【path: '/search/:keyword',】
this.$router.push('/search/'+this.keyword)

// 字符串形式传递query参数
this.$router.push('/search?keyword='+this.keyword)

// 模板字符串形式传递参数,与字符串传递参数的形式类似

// 对象形式传递query参数
this.$router.push({
    path: '/search',
    query: {
        keyword: this.keyword
    }
})

// 对象形式传递paraams参数
// 注意:使用params传递参数时,需要通过name属性传递,而不能通过path属性
this.$router.push({
    name: 'search',
    params: {
        keyword: this.keyword
    }
})

// 通过字符串和模板字符串传递参数这两种方法都不常用,经常使用对象形式传递参数

3、路由组件通过props传递数据的三种写法(不常用)【个人感觉很鸡肋】

备注:在接收参数的路由组件上进行设置

// 布尔值形式。只能传递prams参数
props: true,

// 对象写法。额外给路由组件传递一些props
props: {
    a: 1,
    b: 2
},

// 函数写法。可以传递params参数和query参数
props: (route)=>{
    // route表示当前路由信息
    console.log(route);
    return {
        keyword: route.params.keyword,
        k: route.query.k
    }

}

接收参数时和父子组件传参时接收props参数一致 props: ['keyword','k','a','b']