vue 中 this.route.query 和 this.route.params & query传参和params传参的使用和区别
1.query传参:
路由:
var router = new VueRouter({routes: [{ path: '/login', component: login },{ name:'register',path: '/register', component: register } ]})
导航:
//注意:这是query 两种传参方式 一种是直接把字符串传过去 一种是传描述目标位置的对象
登录 注册 或注册 同于:this.$router.push('/login?id=10&name=zs')this.$router.push({path:'/register',query:{id:5,name:'lili'}})
或this.$router.push({name:'register',query:{id:5,name:'lili'}})
注意:jquery可以通过name或path来引入路由
2.params传参
路由:
var router = new VueRouter({routes: [{ path: '/login/:id/:name', component: login },// 这里不传入对应的参数(:/id/:name) 刷新页面 参数会消失,页面中就丢失了数据{ name:'register', path: '/register/:id/:name', component: register }]})
导航:
// 注意:这是 params 两种传参方式 一种是直接跳转把字符串传过去 一种是传描述目标位置的对象登录 注册 等同于:this.$router.push('/login/12/ls')this.$router.push({name:'register',params:{id:10,name:'lili'}})
注意:params只能通过name来引入路由 ,path会undefined
jquery传参和params传参的区别
1.用法上:
1.上文已经提到query可以用name或者path来引入
2.params必须要用name来引入,接收参数都是类似的,分别是
this.$route.query.name 和 this.xxxx.params.name
2.地址栏表现形式上:
query:
/login?id=10&name=zs
params:
/login/12/ls
**注意:**这里的12和ls 对应的是/:id/:name 这两个参数可以不写 那么就不会在地址栏上显示 不过刷新页面参数会消失 写上参数刷新页面 参数不会消失
1.query方式传参和接收参数
传参:
this.$router.push({path:'/detail/:id',query:{id:id}
})
接收参数
this.$route.query.id
2.params方式传参和接收参数
传参:
this.$router.push({name:'Detail',params:{id:id}
})
接收参数:
this.$route.params.id
params传参,push里面只能是 name:‘xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!
另外,二者还有点区别:
1.接收参数
// query通过this.$route.query接收参数
created () {const id = this.$route.query.id;
}// params通过this.$route.params来接收参数
created () {const id = this.$route.params.id;
}
1.切换路由
// query通过path切换路由
前往Detail页面
// params通过name切换路由
前往Detail页面 复制代码
方式一:监听$router
复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch(监测变化) $route 对象:
watch:{'$route'(to,from){//对路由变化作出响应}
}
方式二:唯一值key属性
Vue 为你提供了一种方式来声明“这两个元素是完全独立的——不要复用它们”。只需添加一个具有唯一值的 key 属性即可
computed: {key(){return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date()}
}
使用computed属性和Date()可以保证每一次的key都是不同的,这样就可以如愿刷新数据了。
实践
1.定义路由
{path: '/hse/problem/prMain/deal/:id',component: () => import('@/views/hse/Problem/PrDeal.vue'),meta: {keepAlive: true}},
2.动态路由传参
handleDeal(id){this.$router.push({path: `/hse/problem/prMain/deal/${id}`,params: {id: id}})}
3.监听路由
watch:{//监听路由$route(){if(this.$route.params!==null){this.paramId = this.$route.params.id;}},paramId(newVal,oldVal){if(newVal !== undefined && newVal !== null){//初始化数据 this.init();}}}
4. init方法初始化数据
methods:{//初始化数据init(){let vm = this;vm.$nextTick(()=>{vm.$axios.get(`/hse/sim/prProblem/v1/get/${vm.dataId}`).then(reply=>{vm.form = reply.data;}).catch(e=>{vm.$toast.fail(e);})})}
}
实例
routes: [// 写法 (1){ //在路由中显示传递的参数 path: '/skipIn/:name/:age', //传递两个参数name: 'SkipIn', //跳转页面的名字component: SkipIn //注册组件},// 写法 (2)// { // path: '/skipIn',// name: 'SkipIn',// component: SkipIn// }
]
跳转之前的页面
路由跳转
跳转之后的页面
{{msg}}返回 {{params}}