How to configure Vue router to respond to query strings?

泄露秘密 提交于 2019-12-12 20:59:22

问题


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:


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.



来源:https://stackoverflow.com/questions/41167814/how-to-configure-vue-router-to-respond-to-query-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!