我们知道,我们可以用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?doctor 们似乎没有提到这一点.

例如,我想要:

<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#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;
    }
  }
};

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

Vue.js相关问答推荐

Vue3组合-如何在组件卸载时注销回调

vue : 多个样式的类绑定在一个

vue 3 中范围样式和深度样式的问题

vue js导航到带有问号的url

Defer推迟执行,直到外部脚本加载到 Vue.js

我可以从手表调用方法并安装吗?

Vuetify v-data-table ,如何在 HTML 中呈现标题文本?

apache上的Vue-router,子目录下的SPA,只能通过重定向访问页面

React.js 是否有类似 Vue.js

使用 Blade/Mustache 模板混合 Laravel 和 Vue.Js

如何在 VueJS 中访问 [__ob__: Observer] 的元素?

Vuex 存储数据总是驻留在内存中?

Vue - 如何在 v-if 或组件中使用窗口对象

如何在 Vue.js 插槽范围内传递方法

使计算的 Vue 属性依赖于当前时间?

beforeCreate 挂钩中的 Vue 2.1 调用方法不起作用

TypeError: Object(...) 不是 Vue 中的函数

使用 CloudFront 部署在 S3 上的 VueJS 应用程序的指定的密钥不存在

Vue.js 中的条件 依赖于props值?

使用 vue.js 获取调用元素