众所周知,我们可以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>
有这种方法吗?
以下是Vue#1.0解决方案:
传递路线对象,例如:
const route = {name: 'route_name', params: {...}, query: {...}}
方法:vm.$router.stringifyPath
返回网址路径。
然后,我们可以使用该路径生成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;
}
}
};
现在,我们可以自由地共享指向其他地方的链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句