我们知道,我们可以使用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之外轻松获取域名部分。顺便说一句:在创建const router = new VueRouter ...
之后,您可以使用router.history.current.path;
获取URL。这个方法也可以获得像/reg
这样的URL。
以下是Vue#1.0解决方案:
传递路径对象,如:
const route = {name: 'route_name', params: {...}, query: {...}}
方法:vm.$router.stringifyPath
返回url路径。
然后我们可以使用该路径生成href
网址。
但我们还需要知道路由器系统模式是什么,所以:
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
}
}