当前位置: 首页 > Web前端 > vue.js

Vue路由传递参数有3个选项

时间:2023-04-01 10:57:47 vue.js

选项1路由后面跟着参数特点:1参数显示在地址栏。2刷新页面,参数不会消失。案例:代码示例:------------------------router.js-----------------------------------------constroutes=[{path:'/news/:newsId',//路由后跟自定义参数变量name:'News',component:()=>import('../views/news.vue')}]-------------------------------跳转链接----------------------------------------News//直接跟在路由后面的参数或者//特别注意:这种跳转方式会导致News组件lifehooks不会触发。还有其他方法可以解决此问题,这里只是解释一下路由参数的用法跳转到新闻页面jumpToNews(param){this.$router.push({path:`/news/${param}`})}------------------------News组件获取路由参数------------------------------------mounted(){this.newsId=this.$route.params.newsId//通过$route.params获取指定参数(变量)},方案2$router.push({path:'',query:{id:''}})特点:1参数显示在地址栏。2刷新页面,参数不会消失。案例:代码示例:--------路由--------------------------------------constroutes=[{path:'/news',name:'News',component:()=>import('../views/news.vue')}]------跳转方法----------------------------------jumpToNews(param){this.$router.push({path:`/news`,query:{newsId:param}})}--------News组件获取路由参数-----------------------mounted(){this.newsId=this.$route.query.newsId},方案3匹配路由中的name属性,通过params传参特点:1参数不会显示在地址栏。2刷新页面,参数消失。案例:代码示例:--------路由--------------------------------------constroutes=[{path:'/news',name:'News',component:()=>import('../views/news.vue')}]------跳转传输方式--------------------------------jumpToNews(param){this.$router.push({name:'News',params:{newsId:param}})}--------News组件获取路由参数------------------------mounted(){this.newsId=this.$route.params.newsId},