【问题标题】:Cannot use Vue-Router to get the parameters in the URL无法使用 Vue-Router 获取 URL 中的参数
【发布时间】:2021-09-29 15:39:27
【问题描述】:

今天尝试使用Vue-Router(在Vue-CLI中)获取URL参数时遇到困难($route.query为空),代码如下。

代码用途:获取URL后面携带的参数(如“http://localhost:8080/#/?client_id=00000000000077”中的client_id)

项目文件结构:

路由器/index.js:

App.vue(获取URL参数部分代码):

这部分代码的运行结果:

【问题讨论】:

    标签: vue.js vue-router vuejs3


    【解决方案1】:

    我不确定为什么 $router.currentRoute$route 不匹配,但如果您需要在 mounted() 中使用 $router.currentRoute.query.client_id,您可以简单地使用它。

    另一种解决方法是在$route.query.client_id 上使用$watch

    export default {
      mounted() {
        const unwatch = this.$watch('$route.query.client_id', clientId => {
          console.log({ clientId })
    
          // no need to continue watching
          unwatch()
        })
      }
    }
    

    或组合 API 中的 watch

    import { watch } from 'vue'
    import { useRoute } from 'vue-router'
    
    export default {
      mounted() {
        console.log({
          route: this.$route,
          router: this.$router,
        })
      },
      setup() {
        const route = useRoute()
    
        const unwatch = watch(() => route.query.client_id, clientId => {
          console.log({ clientId })
    
          // no need to continue watching
          unwatch()
        })
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 2017-05-21
      • 2021-06-23
      • 1970-01-01
      • 2018-09-15
      • 2019-08-11
      • 2017-07-02
      • 2017-03-15
      • 2017-11-30
      相关资源
      最近更新 更多