How to configure Vue router to respond to query st

2019-07-13 09:01发布

My router in configured as follows. It works and does what it's supposed to.

import Demo1 from "../vuex_modules/demo/demo1.vue"
import Demo2 from "../vuex_modules/demo/demo2.vue"

export const routes = [
  { path: "/demo/demo1", component: Demo1 },
  { path: "/demo/demo2", component: Demo2 }
];

Now, I need to match me some query strings. When I click in one of the views routed to above, I want the object pushed to the router to look like this.

export default {
  methods: {
    clicky: function(row) {
      this.$router.push({ path: "", query: { id: row } });
    }
  }
}

I want the new URL, with ?id=123 added, to lead to another page (while demo2.vue is the table view, demo2_id.vue is supposed to be displayed upon a click and present details for the particular row being clicked.

According to Vue router docs, I'm suppose to add a colon when a part of URL is dynamic. I've tried different approaches, including the one below. I'm not routed to the page requested, though. Instead, I dwell still on the original page.

import Demo1 from "../vuex_modules/demo/demo1.vue"
import Demo2 from "../vuex_modules/demo/demo2.vue"
import Demo2_Id from "../vuex_modules/demo/demo2_id.vue"

export const routes = [
  { path: "/demo/demo1", component: Demo1 },
  { path: "/demo/demo2", component: Demo2 },
  { path: "/demo/demo2?:id", component: Demo2_Id }
];

Goolearching for vue router query strings leads to nothing that I can regard as useful (possibly due to ignorance)...

1条回答
Luminary・发光体
2楼-- · 2019-07-13 09:29

Case 1:

Following routes are two same route:

{ path: "/demo/demo2", component: Demo2 },
{ path: "/demo/demo2?:id", component: Demo2_Id }

Case 2:

While following are different:

{ path: "/demo/demo2", component: Demo2 },
{ path: "/demo/demo2/:id", component: Demo2_Id }

In first case: /demo/demo2?:id=213, you can get id as $route.query.id while in second case: /demo/demo2/:id, you will get id as $route.params.id.

Now if you want to have routes as in case 1: You will have single row in routes file and single route:

{ path: "/demo/demo2", component: Demo2 },

and you can write code to detect whether $route.query.id is present or not and load component accordingly with use of v-if

If you want to have routes as in case 2: you can add above two lines in routes file and treat them as two different routes.

查看更多
登录 后发表回答