Vue路由query 和 params 传参的区别

x33g5p2x  于2021-10-20 转载在 Vue.js  
字(2.1k)|赞(0)|评价(0)|浏览(460)

通过 url 传递参数控制页面显示数据的两种方式

1. query 传统问号传参

  • url 格式:xxx.com/product?id=123
  • 模板内获取数据:this.$route.query.id

2. params 动态路由匹配

  • url 格式:xxx.com/product/123
  • 模板内获取数据:this.$route.params.id
  • 注意这个方式参数字段名 id 要在路由配置中定义 用冒号的形式标记
  • 参数可以继续拼接 /student/:id/:name/:age/:address
  • 他必须严格按照 url 的配置格式访问

3. 如何选择哪一个传参方式

两个并没有高低之分

  • 动态路由, 优点 ,好看整齐 缺点 必须预先定义, 如果参数多起来多起来不好管控
  • 问号的形式 灵活随意想改就改, 想加就加, 缺点就是太丑陋了, 也不直观
  1. params:/router1/:id //router1/123,/router1/789 ,这里的id叫做params
  2. query:/router1?id=123 , //router1?id=456 ,这里的id叫做query。

query 传参配置的是path,而params传参配置的是name,在params中配置path无效

query在路由配置不需要设置参数,而params必须设置

query传递的参数会显示在地址栏中

params传参刷新会无效,但是query会保存传递过来的值,刷新不变 ;

接收参数使用this.$router后面就是搭配路由的名称就能获取到参数的值

  1. //query:
  2. {
  3. path: '/home',
  4. name: Home,
  5. component: Home
  6. }
  7. // params:
  8. {
  9. path: '/home/:id',
  10. name: Home,
  11. component: Home
  12. }

接口封装

  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import Vue from 'vue'
  4. import store from '@/store'
  5. // 创建一个 axios 实例
  6. const service = axios.create({
  7. withCredentials: true, // send cookies when cross-domain requests
  8. timeout: 5000 // request timeout
  9. })
  10. // 请求拦截
  11. service.interceptors.request.use(
  12. config => {
  13. // do something before request is sent
  14. if (config.isLoading) loadingInstance = Vue.prototype.$baseLoading()
  15. if (process.env.NODE_ENV === 'development') {
  16. config.headers['debugMode'] = 'true'
  17. }
  18. return config
  19. },
  20. error => {
  21. return Promise.reject(error)
  22. }
  23. )
  24. // 响应拦截
  25. service.interceptors.response.use(
  26. response => {
  27. const res = response.data
  28. if (res.intRes === 1) { // 登录请求退出
  29. if (store.getters.empId) { // 如果登录过,提示会话失效
  30. Vue.prototype.$baseConfirm('会话已失效请重新登录', '会话失效', () => {
  31. window.location.href = process.env.VUE_APP_BASE_SSO_URL + window.location.href
  32. })
  33. }
  34. return res
  35. }
  36. if (res.intRes !== 0) {
  37. const msg = isEmpty(res.objRes) ? res.msgRes : res.objRes
  38. Vue.prototype.$baseMessage(msg, 'warning')
  39. return Promise.reject(res)
  40. } else {
  41. return res
  42. }
  43. },
  44. error => {
  45. return Promise.reject(error.response)
  46. }
  47. )
  48. // get 和 post 请求封装
  49. export default {
  50. get(url,params){
  51. return service.get(url,{params:params})
  52. },
  53. postJson(url,data){
  54. return service.post(url,data,
  55. {
  56. headers:{'ContentType':'application/json'}
  57. })
  58. },
  59. postForm(url, data, isLoading = true) {
  60. return service.post(url, qs.stringify(data), {
  61. isLoading: isLoading,
  62. headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  63. })
  64. },
  65. }

文案来源https://cloud.tencent.com/developer/article/1848975 ,仅用于学习,侵权立删

相关文章

最新文章

更多