【问题标题】:Listen to onpopstate with Vuejs without vue-router在没有 vue-router 的情况下使用 Vuejs 监听 onpopstate
【发布时间】:2021-01-28 17:07:46
【问题描述】:

我正在使用带有 laravel 的 vue.js,并且我正在使用带有 laravel 刀片文件的 vue 组件。当我按下后退导航按钮转到上一页时,我想重新加载页面。我有这个代码的目的:

created() {
       window.onpopstate = function(event) {
       location.reload();
    };

这不起作用。我可以使用浏览器的后退按钮返回,但没有重新加载。我怎样才能达到结果?同样,我没有使用 vue-router。我正在使用laravel的路由加载刀片文件,刀片文件包含vue文件。 刀片文件:

@extends('layouts.app')
@section('content')
  <vue-component></vue-component>
@endsection

【问题讨论】:

    标签: javascript jquery laravel vue.js


    【解决方案1】:

    我认为您的问题是浏览器在后退按钮上保持状态。这是 vue 中与基于 chrome 的浏览器 here is more info about it 相关的一个已知错误。要在不重新加载页面的情况下解决此问题,您需要在 pageshow 事件中初始化 Vue,如下所示:

    const initVue = () => {
        return new Vue({
            el: '#app',
            store
        });
       }
        const app = window.addEventListener('pageshow', () => {
            initVue();
        })
    

    但要在 Safari 中解决此问题,您必须重新加载页面(将其应用到您的主布局刀片中)。

      (function () {
                window.onpageshow = function (event) {
                if (event.persisted) {
                    window.location.reload();
                    }
                };
            })();
    

    或者,如果您真的想通过在使用后退按钮时重新加载页面来解决此问题,那么您需要为您的组件使用这样的方法,或者您可以在主布局刀片中使用它以将其应用到任何地方:

    methods: {
        checkBackButton: function() {
                if (
                    window.performance &&
                    window.performance.navigation.type ===
                        window.performance.navigation.TYPE_BACK_FORWARD &&
                    this.type === "main"
                ) {
                    window.location.reload();
                }
            }
    },
    
    mounted() {
       this.checkBackButton();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 2017-09-07
      • 2015-01-02
      • 1970-01-01
      • 2021-05-23
      • 2010-10-28
      • 2018-10-01
      • 2021-01-25
      相关资源
      最近更新 更多