簡體   English   中英

Vue 1.x / 2.x:從$ route對象獲取vue-router路徑url

[英]Vue 1.x/2.x: Get vue-router path url from a $route object

我們知道,我們可以使用vue-route來包裝一些路徑路徑。

<!-- vue 1.x -->
<a v-link="{name: 'route_name', params: {id: 1}}"></a>

並在vue2:

<!-- vue 2.x -->
<router-link :to="{name: 'route_name', params: {id: 1}}"></router-link>

現在,我想顯示一個鏈接網址供用戶復制,所以我想知道是否有辦法從路由對象返回絕對路徑網址? 似乎文檔沒有提到這一點。

例如,我想:

<template>
  <label>Copy the address</label>
  <input value="url" />
</template>

<script>
  export default {
    computed: {
      url() {
        const route = {name: 'route_name', params: {id: 1}};
        // !! The bellow shows what I may want.
        return this.$router.getLink(route);
      },
    }.
  };
</script>

有這樣的方法嗎?

對於希望這樣做的未來人們

我相信這是Vue 2.x的方式

var path = this.$router.resolve({name: 'SomePath', params: {id: 1}}).href

然后,如果你想要完整的網址,你會做

var fullUrl = window.location.origin + "/" + path

在Vue 2.0中,您可以嘗試我的方式: this.$route.path可以獲得沒有域的URL路徑。 例如: http://localhost:8000/#/reg只獲取/reg部分; 您可以在VueRouter之外輕松獲取域名部分。 BTW:在創建const router = new VueRouter ... ,你可以使用router.history.current.path;獲取URL router.history.current.path; 此方法也可以像/reg一樣獲取URL。

以下是Vue#1.0解決方案:

傳遞路徑對象,如:

const route = {name: 'route_name', params: {...}, query: {...}}

方法: vm.$router.stringifyPath返回url路徑。

然后我們可以使用該路徑生成一個href url。

但我們還需要知道路由器系統模式是什么,所以:

export default {
  methods: {
    getUrlFromRoute(route) {
      const vm = this;
      let path = vm.$router.stringifyPath(route);
      if (vm.$router.mode === 'hash') {
        if (vm.$router.history.hashbang) {
          path = '!' + path;
        }
        path = '#' + path;
      }
      // finally we add the absolute prefix before that
      if (path[0] === '#') {
        // hash mode join
        path = location.origin + location.pathname 
             + (location.query||'') + path;
      } else if(path[0] === '/') {
        // absolute path
        path = location.origin + path;
      } else {
        // relative path
        path = location.origin + location.pathname.replace(/\/[^\/]+$/, '/') + path;
      }
      return path;
    }
  }
};

現在我們可以自由地分享到其他地方的鏈接。

一些答案似乎有些過分,雖然我找不到任何開箱即用的解決方案,但我決定只使用javascript中的內置函數來完成它。

return window.location.origin + '/route-path?id=1';

簡而言之, window.location返回當前URL的協議,主機名和端口號。 然后只需附加所需的其余URL。

我之前的回答已被刪除......

我使用https://github.com/vuejs/vuex-router-sync然后在需要path組件中我已經計算了屬性。 簡單,直接的解決方案。

在您的入口點,通常是main.js您必須放置:

import { sync } from 'vuex-router-sync'
import store from './vuex/store' // vuex store instance
import router from './router' // vue-router instance

sync(store, router) // done.

然后在你需要path的組件中,當然在<script>

computed: {
  path () {
    return store.state.router.path
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM