Vue.parámetros de consulta js


¿Cómo puedo obtener parámetros de consulta en vue?js?

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

¿No puede encontrar una manera de obtener o necesito usar JS puro o alguna biblioteca para esto?

Author: Bharathvaj Ganesan, 2016-03-10

5 answers

De acuerdo con los documentos de objeto ruta, usted tiene acceso a un objeto $route de sus componentes, que exponen lo que necesita. En este caso

//from your component
console.log(this.$route.query.test) // outputs 'yay'
 102
Author: Yerko Palma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-30 15:27:01

Respuesta más detallada para ayudar a los novatos de VueJS.

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});
 19
Author: Sabyasachi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-17 06:51:13

Sin vue-route, divide la URL

var vm = new Vue({
  ....
  created()
  {
    let uri = window.location.href.split('?');
    if (uri.length == 2)
    {
      let vars = uri[1].split('&');
      let getVars = {};
      let tmp = '';
      vars.forEach(function(v){
        tmp = v.split('=');
        if(tmp.length == 2)
        getVars[tmp[0]] = tmp[1];
      });
      console.log(getVars);
      // do 
    }
  },
  updated(){
  },

Otra solución https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:

var vm = new Vue({
  ....
  created()
  {
    let uri = window.location.search.substring(1); 
    let params = new URLSearchParams(uri);
    console.log(params.get("var_name"));
  },
  updated(){
  },
 13
Author: erajuan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-01 00:10:54

Puede usar vue-router.Tengo un ejemplo a continuación:

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()
  }
})

Nota: En la función beforeRouteEnter no podemos acceder a las propiedades del componente como: this.propertyName.Es por eso que he pasado el vm a next function.It es la forma recomendada de acceder a la instancia de vue.En realidad, el vm significa vue instance

 1
Author: roli roli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-20 12:59:24

Otra forma (suponiendo que esté usando vue-router), es mapear el param de consulta a un prop en su enrutador. Luego puede tratarlo como cualquier otro prop en su código de componente. Por ejemplo, agregue esta ruta;

{ 
    path: '/mypage', 
    name: 'mypage', 
    component: MyPage, 
    props: (route) => ({ foo: route.query.foo })  
}

Luego en su componente puede agregar el prop como normal;

props: {
    foo: {
        type: String,
        default: null
    }
},

Entonces estará disponible como this.foo y puedes hacer lo que quieras con él (como establecer un vigilante, etc.).)

 1
Author: Mike P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-24 16:03:45