Vue 1.x/2.x:从 $route 对象获取 vue-router 路径 url

新手上路,请多包涵

正如我们所知,我们可以使用 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>

现在,我想显示一个链接 url 供用户复制,所以我想知道是否有办法从路由对象返回绝对路径 url?文档似乎没有提到这一点。

例如,我想要:

 <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>

有这样的方法吗?

原文由 Alfred Huang 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 618
2 个回答

下面是 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;
    }
  }
};

现在我们可以自由地将链接分享到其他地方。

原文由 Alfred Huang 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于未来希望这样做的人

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

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

那么如果你想要完整的网址,你会做

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

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题