nar*_*upo 13 vue.js vue-router
我想获取上一页链接或网址vue-router.像这样.怎么做?
const link = this.$router.getPrevLink(); // function is not exist?
this.$router.push(link);
Run Code Online (Sandbox Code Playgroud)
近概念是this.$router.go(-1).
this.$router.go(-1);
Run Code Online (Sandbox Code Playgroud)
小智 41
对于 Vue 3 和 Vue Router 4,我的解决方案是:
this.$router.options.history.state.back
Run Code Online (Sandbox Code Playgroud)
最终代码:
export default defineComponent({
name: 'Error404',
data () {
return {
lastPath: null
}
},
created () {
this.lastPath = this.$router.options.history.state.back
},
computed: {
prevRoutePatch () {
return this.lastPath ? this.lastPath : '/dashboard'
}
}
})
Run Code Online (Sandbox Code Playgroud)
问候。
Hus*_*him 31
所有vue-router的导航警卫都接收前一个路由作为from参数.
每个守卫功能都有三个参数:
to: Route:导航到的目标Route对象.
from: Route:当前路线被导航离开.
next: Function:必须调用此函数来解析钩子.该操作取决于提供给下一个的参数
作为一个示例,您可以使用beforeRouteEnter组件内导航防护来获取先前的路径并将其存储在您的数据中.
...
data() {
return {
...
prevRoute: null
}
},
beforeRouteEnter(to, from, next) {
next(vm => {
vm.prevRoute = from
})
},
...
Run Code Online (Sandbox Code Playgroud)
然后,您可以this.prevRoute.path转到上一个路由,或访问from以获取以前的URL.
如果先前的 url 不存在,此路由解决方案将回退到静态 url。
<template>
<div>
<router-link :to="prevRoutePath">Previous Page</router-link>
<router-link to="/">Home Page</router-link>
</div>
</template>
<script>
export default {
beforeRouteEnter(to, from, next) {
next(vm => {
vm.prevRoute = from;
});
},
computed: {
prevRoutePath() {return this.prevRoute ? this.prevRoute.path : '/'},
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
虽然这个答案很好,但在弹出状态导航(即当用户单击后退按钮时)的情况下,收到的路线并不总是历史上之前的路线。
因此,如果您使用 Vuex,这里有一个遵循此行为的代码片段:
const store = new Vuex.Store({
state: {
routerHistory: [],
},
});
const router = new VueRouter({
mode: 'history',
scrollBehavior(to, from, savedPosition) {
const fromHistory = Boolean(savedPosition);
if (fromHistory && store.state.routerHistory.length > 0) {
store.state.routerHistory.splice(-1, 1);
} else {
store.state.routerHistory.push(from);
}
return savedPosition || { x: 0, y: 0 };
},
});
Run Code Online (Sandbox Code Playgroud)
实现后,您可以为商店内的先前路由定义一个 getter:
const store = new Vuex.Store({
// ...
getters: {
previousRoute: (state) => {
const historyLen = state.routerHistory.length;
if (historyLen == 0) return null;
return state.routerHistory[historyLen - 1];
},
},
});
Run Code Online (Sandbox Code Playgroud)
此代码使用scrollBehavior 钩子,如果它是popstate 导航,则它仅接收savedPosition 参数。感谢 Vuex,我们可以将所有路由存储在一个数组中(跨多个页面)。
| 归档时间: |
|
| 查看次数: |
12510 次 |
| 最近记录: |