我怎样才能获得Vue路由器的历史记录?

时间:2017-05-01 05:39:26

标签: javascript vue.js

我需要检测Vue路由器的历史记录中是否还有其他条目要返回。我会用它来检测是否触发退出应用程序功能。只要应用程序可以返回到上一页,它应该,但是当它到达结束时它应该退出。

2 个答案:

答案 0 :(得分:0)

所以我遇到了类似的问题,同时运行angularjs和vue.js应用程序。一旦vue.js历史记录堆栈为空,请转到angularjs。这是我使用的vuex解决方案:

/** store/history.ts */

import { clientRouter } from '@/views'
import { Route } from 'vue-router'
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex'
import { IRootState } from '.'

export interface IHistoryState {
    history: Route[]
}

const historyState: IHistoryState = {
    history: []
}

const getters: GetterTree<IHistoryState, IRootState> = {
    history: state => state.history
}

const mutations: MutationTree<IHistoryState> = {
    pop: state => state.history.pop(),
    push: (state, route: Route) => state.history.push(route)
}

const actions: ActionTree<IHistoryState, IRootState> = {
    back: context => {
        const history = context.state.history
        if (history.length === 1) {
            window.location.href = '/angular.html'
        }
        else {
            clientRouter.back()
        }
    },
    record: (context, route: Route) => {
        const history = context.state.history

        // Reloading same page
        if (history.length && history[history.length - 1].name === route.name) {
            context.commit('pop')
            context.commit('push', route)
            return false
        }
        // Going back
        else if (history.length > 1 && history[history.length - 2].name === route.name) {
            context.commit('pop')
            return false
        }
        else {
            context.commit('push', route)
            return true
        }
    }
}

export default {
    state: historyState,
    getters,
    mutations,
    actions,
    namespaced: true
} as Module<IHistoryState, IRootState>

由于SSR,我在这里使用clientRouter,但是您可以使用任何路由器。还有它的打字稿,如果需要,我可以将其转换为香草。使用这种方法,您应该始终返回此处的操作。然后,您所需要做的就是记录历史记录,我在主要的应用程序组件上使用了以下代码:

/** app.vue */

@Action('history/record') recordHistory: (to: Route) => forward:boolean

@Watch('$route')
function (to: Route) {
    // Push to history
    this.recordHistory(to)

    // Analytics
    analytics.trackPageView()
}

答案 1 :(得分:-1)

关于&#34; 您的问题有点不清楚只要该应用可以返回上一页&#34; - 之前您是指浏览器历史记录中的任何页面还是应用程序中的页面?

如果它是第一个,你可以这样做:

history.back();
app.exitProcess();

因此,如果浏览器无法返回历史记录,则您的脚本只能访问exitProcess

您也可以查找document.referrer,但它通常是空的或未定义的值。

然而,如果它是第二个选项,那么我觉得你应该保留一个历史状态,以便知道最后一个选项是什么时候?在您的应用内部执行的操作以及何时结束,即可返回其他网站。

相关问题