匹配vue js路由与查询字符串?

时间:2018-04-27 01:14:52

标签: vue.js vuejs2

我在这里读到:

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

但它似乎没有让我匹配说:

/mycoolapp?someid=123
是的,我能做到

/mycoolapp/123

但这不是问题

问题是:我可以使用get query参数动态匹配路由吗?

1 个答案:

答案 0 :(得分:5)

您可以通过someid在示例$route.query.someid中访问查询参数。 From $route docs

  
      
  • <强> $route.query

         

    输入:Object

         

    包含查询字符串的键/值对的对象。对于   例如,对于路径/foo?user=1,我们得到$route.query.user == 1。如果   没有查询该值将是一个空对象。

  •   

演示如下:

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>

另一方面,如果要根据查询参数重定向到特定组件,可以使用navigation guards。例如,beforeEach

router.beforeEach((to, from, next) => {
    if (to.query.field === 'email') {
        next({path: '/email'}); // some hypothetical path
    } else {
        next();
    }
});