Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match vue js routes with query string in them?

Tags:

vue.js

vuejs2

I was reading here:

https://router.vuejs.org/en/essentials/dynamic-matching.html

but it doesn't seem to let me match say:

/mycoolapp?someid=123

yes, I could do

/mycoolapp/123

but that is not the question

The question is: can I match routes dynamically with get query parameters?

like image 851
Toskan Avatar asked Apr 27 '18 01:04

Toskan


1 Answers

You can access the query parameters, in your example someid via $route.query.someid. From $route docs:

  • $route.query

    type: Object

    An object that contains key/value pairs of the query string. For example, for a path /foo?user=1, we get $route.query.user == 1. If there is no query the value will be an empty object.

Demo below:

const UserList = {
  template: '#users',
  data() { return { users: [] } },
  created() {
    axios.get('https://jsonplaceholder.typicode.com/users').then(r => this.users = r.data);
  }
};
const User = {
  props: ['uid', 'user'],
  template: '#user'
}

var router = new VueRouter({
  routes: [{
    path: '/',
    component: UserList
  },
  {
    path: '/user/:uid',
    component: User,
    name: 'user',
    props: true
  }]
});

var app = new Vue({
  el: '#app',
  router: router,
  template: '<router-view></router-view>'
});
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-router"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<template id="users" functional>
  <div>
    <ul>
      <li v-for="user in users">
        <div>
          {{ user.name }} - 
          <router-link :to="{name: 'user', params: {uid: user.id, user: user}, query: {field: 'email'}}">(email)</router-link> -
          <router-link :to="{name: 'user', params: {uid: user.id, user: user}, query: {field: 'website'}}">(website)</router-link>
        </div>
      </li>
    </ul>
  </div>
</template>

<template id="user" functional>
  <div class="row">
    <b>{{ user.name }}</b><br>
    {{ $route.query.field }}: {{ user[$route.query.field] }}<br>
    <router-link :to="{path: '/'}">back</router-link>
  </div>
</template>

<div id="app">
  <p>{{ message }}</p>
</div>

On the other hand, if you want to redirect to a specific component depending on the query parameters, you can use navigation guards. For instance, beforeEach:

router.beforeEach((to, from, next) => {
    if (to.query.field === 'email') {
        next({path: '/email'}); // some hypothetical path
    } else {
        next();
    }
});
like image 195
acdcjunior Avatar answered Nov 12 '22 13:11

acdcjunior