How can I get query parameters from a URL in Vue.js?

后端 未结 9 1484
甜味超标
甜味超标 2020-12-12 13:47

How can I fetch query parameters in Vue.js?

E.g. http://somesite.com?test=yay.

Can’t find a way to fetch or do I need to use pure JS or some lib

9条回答
  •  北海茫月
    2020-12-12 14:30

    You can use vue-router.I have an example below:

    url: www.example.com?name=john&lastName=doe

    new Vue({
      el: "#app",
      data: {
        name: '',
        lastName: ''
      },
      beforeRouteEnter(to, from, next) {
          if(Object.keys(to.query).length !== 0) { //if the url has query (?query)
            next(vm => {
             vm.name = to.query.name
             vm.lastName = to.query.lastName
           })
        }
        next()
      }
    })
    

    Note: In beforeRouteEnter function we cannot access the component's properties like: this.propertyName.That's why i have pass the vm to next function.It is the recommented way to access the vue instance.Actually the vm it stands for vue instance

提交回复
热议问题