Alf*_*ang 7 mvvm ecmascript-6 vue.js vue-router vuejs2
众所周知,我们可以vue-route用来包装一些路径。
<!-- vue 1.x -->
<a v-link="{name: 'route_name', params: {id: 1}}"></a>
Run Code Online (Sandbox Code Playgroud)
在vue2中:
<!-- vue 2.x -->
<router-link :to="{name: 'route_name', params: {id: 1}}"></router-link>
Run Code Online (Sandbox Code Playgroud)
现在,我想显示供用户复制的链接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>
Run Code Online (Sandbox Code Playgroud)
有这种方法吗?
Dan*_*Dan 15
对于将来希望这样做的人
我相信这是Vue 2.x的方式
var path = this.$router.resolve({name: 'SomePath', params: {id: 1}}).href
Run Code Online (Sandbox Code Playgroud)
然后,如果您想要完整的网址,则可以
var fullUrl = window.location.origin + "/" + path
Run Code Online (Sandbox Code Playgroud)
下面是 Vue#1.0 的解决方案:
传递一个路由对象,例如:
const route = {name: 'route_name', params: {...}, query: {...}}
该方法:vm.$router.stringifyPath返回 url 路径。
然后我们就可以使用该路径来生成一个hrefurl。
但我们还需要知道路由器系统模式是什么,所以:
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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
现在我们可以自由地将链接分享到其他地方。
| 归档时间: |
|
| 查看次数: |
8421 次 |
| 最近记录: |