vue常用的导航跳转带参数this.$router.push

本文讲解了如何在Vue应用中通过$router.push进行搜索功能的实现,包括使用命名路由、动态参数和query对象,并提供了两种不同场景下的代码优化,帮助开发者理解和改进路由参数传递方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

this.$router.push({name:'search',params:{keyword:this.keyword},query:{k:this.keyword}});

这是最常用的 在router.js定义好

{
    path:'/search/:keyword',//keyword为占位使用 可显示到url上
	component:Search,
	meta:{show:true},
	name:'search' //为搜索定义一个名字 
}

点击搜索

methods:{
			goSearch(){
			    	// this.$router.push({name:'search',params:{keyword:this.keyword},query:{k:this.keyword}});
				let location ={name:'search',params:{keyword:this.keyword || undefined}};
				if(this.$route.query){  //如果有query参数 加上以下代码
					location.query = this.$route.query
					this.$router.push(location);
				}
			}
		}

点击导航按钮搜索

点击导航的代码

methods:{
			goSearch(event){
				let data = event.target.dataset;
				
				//把值都取出来
				let {categoryname,category1id,category2id,category3id} = data;
				//整理跳转的参数
				let location = {name: 'search'};
				let query    = {categoryName:categoryname}
				if(category1id){//往query里增加categoryid
					query.category1id = category1id
				}else if(category2id) {
					query.category2id = category2id
				} else if(category3id){
					query.category3id = category3id
				}
				
				//把location和query参数合并
				location.query = query;
				
				//加入搜索框搜索的param参数
				if(this.$route.params){
					location.params = this.$route.params
				}
				
				
				this.$router.push( location );
			},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值