路由跳转
两种跳转方式:
方式一: 父组件中,<router-link to="要跳转的路径"> </router-link> |
方式二:子组件的事件js代码中,$router.push|replace方法,this.$router.push("/路径") |
路由传递参数
两种跳转方式:
方式 一:字符串形式
- 跳转事件js中,设置push的路径
-
methods:{ goSearch(){ goSearch(){this.$router.push('/search/'+this.keyWord+ '?k='+this.keyWord.toUpperCase()) }}
- 路由器设置映射关系时,该路径添加占位
-
routes[{ path: '/search/:keyword?', component: Search, meta: { show: true } }]
- 跳转后,跳转目标 页面获取参数
-
<h1>params参数--{{$route.params.keyword}}</h1> <h1>query参数---{{$route.query.k}}</h1>
方式 二:模板字符串
- 是字符串的升级版本
-
methods:{ goSearch(){ goSearch(){this.$router.push(`/search/'${this.keyWord} ?k=${this.keyWord.toUpperCase()}) }}
方式 三:对象法(常用)
- 在触发事件的中,代码如下
-
methods:{ goSearch(){ this.$router.push({ name:'search', params:{keyWord:this.keyWord}, query:{k:this.keyWord.toUpperCase()} }) }}
routes[{ path: '/search/:keyword', component: Search, meta: { show: true }, name:'search' }]
注意:
1、如何指定params参数可传可不传呢? 设置路由映射关系时,占位符后+问号?
routes:[{
path:'/search/:keyword?',//必须有问号,代表params可传可不传
name:'search',
component:Search,
meta:{show_footer:true}
}]
2、若params传递参数时,为空?路径出问题,如何解决?? || undefined 来处理
methods:{
goSearch(){
this.$router.push({
name:'search',
params:{keyword:''||undefined},
})
}
}