2017-02-14 56 views
0

我正在使用Vue-Router在Vue中執行一個項目。在我的項目中,我有一個名爲'adtag'的參數,它必須在url查詢參數中,有沒有簡單的方法來保存這個參數,路由器怎麼走也沒有。如何在Vue中使用Vue-Router保存URL查詢參數

例如,我有三個頁面:

  1. 本地主機/指數
  2. 本地主機/列表使用VUE路由器<router-link :to="{name:'Detail',query:{id:item.id}}"></router-link>
  3. 本地主機/細節ID = 11

頁變化?

如果我用adtag打開第一頁localhost/index?adtag=123,頁面將會改變與PARAM 'adtag'

  1. 本地主機/索引?adtag = 123
  2. 本地主機/列表?adtag = 123
  3. 本地主機/細節?adtag = 123 & ID = 11
+0

爲什麼你需要那個?這真的很奇怪。也許你可以直接使用Vuex來保存這個密鑰(或者其他任何東西) –

+1

你可以在這個頁面的幫助下做到這一點:https://forum.vuejs.org/t/vue-router-programmatically -append-to-querystring/3655/2和'router.beforeEach'導航衛士,doc:https://router.vuejs.org/en/advanced/navigation-guards.html – nicolast

+0

,但它看起來像完美的用例(如果你需要在後端的標籤)或本地存儲(如果你只需要前端的標籤) – nicolast

回答

0

隨着默認Vue 2.x安裝,路由器文件位於src/router/index.js

我能夠然後檢查是否需要修改請求並添加任何缺少的查詢參數(修改to var顯然沒有效果),然後調用next(.. new rout..)的「重定向」。

缺點:雙打的呼叫路由,因爲它本質上重定向

潛在上升空間:它的工作原理,以及查詢保存邏輯是在同一個地方。

一個警告:在頁面加載時,路由器會觸發並且「from」是一條非常空的路徑(甚至不包括URL中的查詢參數)。因此,我設置了if語句來驗證是否需要放置查詢參數。

import Vue from 'vue' 
import Router from 'vue-router' 
// ... All your other components 

Vue.use(Router) 

const router = new Router({ 
    mode: 'history', 
    routes: [ 
    { 
     path: '/', 
     name: 'Dashboard', 
     component: Dashboard 
    }, 
    // ... All your other routes 
    ] 
}) 

router.beforeEach((to, from, next) => { 
    if (from.query.token && !to.query.token) { 
    if (to.path === from.path) { 
     // console.log('Identical routes detected') 
     return // This is a no-no via the documentation, but a bug in routing to identical routes strips query params, and this prevents that 
    } 
    next({path: to.path, query: {token: from.query.token}}) 
    } 

    next() 
}) 

export default router 
相關問題