河南疫情最新通报百度seo培训
目录
🙋♂️ 实现params传参,刷新页面不丢参
🙋♂️ 实现vue配置可选路由参数
🙋♂️ 参考资料
解决vue 通过 name 和 params 进行页面传参时,刷新页面参数丢失问题以及vue路由实现可选参数
🙋♂️ 实现params传参,刷新页面不丢参
路由配置文件——router.js:
export default new Router({routes: [{path: "/",redirect: "/main",},{path: "/main",name: "Main",component: () => import("@/views/Main.vue"),children: [{//path: '/testPage', //这种方式不配置参数名,页面刷新会丢失参数path: "/testPage/:aaa/:bbb", //这样通过name 和 params进行路由传参时,刷新页面就不会丢失参数aaa和bbb 了。name: "TestPage",component: () => import("@/views/TestPage/TestPage.vue"),},],},],
});
调整函数:
methods: {//路由调整传参测试goRouterTest(){// this.$router.push('/testpage');this.$router.push({ name: 'TestPage', params: { aaa: '111', bbb: '222' } });}
}
这样传参时,地址栏就会出现参数了,这样属性就不会丢失了。
然后,可以选择配合路由解耦来使用
修改路由配置为:
{// path: '/testPage', //这种方式不配置参数名,页面刷新会丢失参数path: '/testPage/:aaa/:bbb', //这样通过name和params进行路由传参时,刷新页面就不会丢失参数aaa和bbb了name: 'TestPage',props: true, //若个要解耦的 到组件中 props 中。component:() => import('@/views/TestPage/TestPage.vue')
}
要调整的组件生命 props:
<template><div class="TestPage">Name路由传参{{ $route.params }}</div>
</template>
<script>
export default {name: "TestPage",props: {//将路由中的参数aaa和bbb解耦到组件上的props上aaa: {type: String,},bbb: {type: String,},},mounted() {console.log("这是路由传的参数aaa",this.aaa,"这是路由传的参数bbb",this.bbb);},
};
</script>
<style scoped>
</style>
最后的效果(刷新页面参数不会丢失):
😉 完美搞定!
当然也可以通过 path(或name) 和 query 的方式进行传参 this.$router.push({path: 路由路径,query: { 要传的参数 } }),但是这就不能进行props解耦了。
🙋♂️ 实现vue配置可选路由参数
假如下面是我们的某个路由:
{path: 'examPaperMultiPurpose/:action/:id', //多加 ? 代表这个参数是可选的。name: 'examPaperMultiPurpose',title: '考卷管理',notKeepAlive: true,props: true,component: () => import ('@/views/exam/examManage/examPaperMultiPurpose.vue'),
}
当我们这样进行页面跳转时:
this.$router.push( { name: 'examPaperMultiPurpose', params: {action: 'add'} } );
很显然我们在跳转时, 没有进行 id 参数 的 传递。我们在控制台也会看到这样的警告。
提醒我们缺少参数,id是一个没有定义的。
当我们有时候不是都想传递每个参数,我们可以把参数配置成可选的。配置方法为:在不想传递的参数后只要多加一个 ? 即可,如下代码:
//新增、编辑、查询考卷
{path: 'examPaperMultiPurpose/:action?/:id?', //多加 ? 代表这个参数是可选的。name: 'examPaperMultiPurpose',title: '考卷管理',notKeepAlive: true,props: true,component: () => import ('@/views/exam/examManage/examPaperMultiPurpose.vue'),
}
这样,我们就把两个参数action 和 id 配置成可选的路由参数了,之后,当我们继续进行上面的方式进行传参时,就不会警告我们 缺少参数了。
🙋♂️ 参考资料
- 响应路由参数的变化
带参数的动态路由匹配 | Vue Router
- 路由组件传参
将 props 传递给路由组件 | Vue Router
- vue路由参数可选
vue路由可选参数,可有可无
- 路由跳转及传参方式汇总
详解Vue中实现路由跳转传参的4种方式