刷新 vue.js 保持活动部分中的页面

Refresh pages in vue.js keep-alive section

我有一个使用 vue-router 的 Vue.js SPA。因为登录后每个页面都需要保持状态(比如进入filters/pagination)这是使用keep-alive完成的:

<keep-alive>
  <router-view/>
</keep-alive>

这很好用,但是当有人注销并再次登录时,由于保持活动状态,我仍然看到相同的过滤器值。

我可以 refresh/purge 这些页面在注销时以某种方式保持活动状态吗?

我不认为有一种简单的方法可以做到这一点(以编程方式)所以你有 2 个选择。

选项 1 将重置状态,这意味着您在内部跟踪初始状态并监听类似注销时发出的内容以重置 组件恢复到初始状态。

选项 2 将简单地换掉 keep-alive 组件,使用如下内容:

<keep-alive v-if="loggedIn">
    <router-view></router-view>
</keep-alive>

<router-view v-else></router-view>

一种使用 Vue 全局事件的方法。

Vue.prototype.$loginState = new Vue();

在您的组件中,在单击注销按钮时触发事件。

function logout(){
    //your codes here to logout and then
    this.$loginState.$emit('logout');
}

在用户登录时看到的组件中,只需通过触发的侦听事件将所有变量设置为默认值 'logout'。

<button @click="resetValues"> Logout </button>
methods: {
    resetValues(){
        this.yourValue = '';
        this.filters = [];
    }
}
created(){
    this.$loginState.$on('logout', this.resetValues)
}

keep alive 组件在 this.$children 内,因此您可能可以遍历这些组件并修改状态。